dtzhfb4869 2017-12-01 04:37
浏览 6
已采纳

如何选择mysql结果?

invoice

+----+-----+---------+-------+
| Sr | BRN |  Name   |  Amnt |
+----+-----+---------+-------+
| 1  | 1   | John    |  10   |
| 2  | 1   | John    |   4   |
| 3  | 2   | Belly   |   4   |
| 4  | 3   | John    |  14   |
| 5  | 4   | John    |   5   |
| 6  | 4   | John    |  14   |
+----+-----+---------+-------+

I want to select all rows except the duplicate BRN. (If there are two/more ge in BRN then it should only select one)

I tried:

SELECT *(DISTINCT BRN) FROM invoice

Expected result:

+-----+---------+-------+
| BRN |  Name   |  Amnt |
+-----+---------+-------+
| 1   | John    |  10   |
| 2   | Belly   |   4   |
| 3   | John    |  14   |
| 4   | John    |   5   |
+-----+---------+-------+
  • 写回答

3条回答 默认 最新

  • dtn43447 2017-12-01 06:52
    关注

    Given the following table:

    +----+-----+---------+-------+
    | Sr | BRN |  Name   |  Amnt |
    +----+-----+---------+-------+
    | 1  | 1   | John    |  10   |
    | 2  | 1   | John    |   4   |
    | 3  | 2   | Belly   |   4   |
    | 4  | 3   | John    |  14   |
    | 5  | 4   | John    |   5   |
    | 6  | 4   | John    |  14   |
    +----+-----+---------+-------+
    

    with the expected results:

    +-----+---------+-------+
    | BRN |  Name   |  Amnt |
    +-----+---------+-------+
    | 1   | John    |  10   |
    | 2   | Belly   |   4   |
    | 3   | John    |  14   |
    | 4   | John    |   5   |
    +-----+---------+-------+
    

    The difficult part is getting the amount, because it is arbitrary, not to mention that the values in Amnt are pretty much worthless in this result.

    If you want distinct BRN, the query would be SELECT DISTINCT BRN FROM invoice

    You might even get away with SELECT DISTINCT BRN, Name FROM invoice

    An intermediate step would be SELECT BRN,Name FROM invoice GROUP BY BRN, Name

    But if you try to include Amnt in the equation, then the query will fail because there's no way for the database to determine which Amnt to show.

    So, you could try this kludge:

    SELECT a.BRN, a.Name, b.Amnt FROM invoice AS a LEFT JOIN invoice AS b ON a.BRN=b.BRN
    

    No guarantees on which Amnt it will pick up, though.

    Hope that helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真