【问题标题】:MySql table merging with sumMySql 表与 sum 合并
【发布时间】:2013-05-23 15:20:27
【问题描述】:

我的 twp 表是这样的。

+----+--------+   +----------+-------+--------+
| id | fruit  |   | fruit_id | color | amount |
+----+--------+   +----------+-------+--------+

结果:

SELECT
  fruit,amount
FROM
  table1,table2
WHERE fruit_id = id

+--------+--------+
| fruit  | amount |
+--------+--------+
| Apple  |      5 |
| Apple  |      5 |
| Cherry |      2 |
| Cherry |      2 |
+--------+--------+

但我想要这个结果:

+--------+--------+
| fruit  | amount |
+--------+--------+
| Apple  |     10 |
| Cherry |      4 |
+--------+--------+

【问题讨论】:

    标签: mysql merge sum


    【解决方案1】:

    您将使用聚合函数 sum()GROUP BY 来获得结果:

    SELECT t1.fruit, sum(t2.amount) Total
    FROM table1 t1
    inner join table2
      on t2.fruit_id = t1.id
    group by t1.fruit
    

    附带说明,您应该使用标准 ANSI 连接语法和 INNER JOIN。

    【讨论】:

    • 这个OK "SELECT fruit, sum(amount) Total FROM table1 inner join table2 on fruit_id = id group by fruit" 然后...
    • @MahmutEsinti 是的,这是正确的,应该返回结果。
    • @MahmutEsinti 您将希望使用 LEFT JOIN 而不是 INNER JOIN
    • @bluefeet 一个更多问题: 我该怎么办,还退回物品where amount = 0 或不在金额表中的水果
    猜你喜欢
    • 2023-04-06
    • 2013-01-24
    • 2012-06-29
    • 2012-06-17
    • 1970-01-01
    • 2012-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多