我有三个相互连接的表。
mysql> select * from tablea;
+----+--------+
| id | name |
+----+--------+
| 1 | Item 1 |
| 2 | Item 2 |
+----+--------+
2 rows in set (0.00 sec)
mysql> select * from tableb;
+----+------+----------+
| id | Aid | name |
+----+------+----------+
| 1 | 1 | B Item 1 |
| 2 | 2 | B Item 2 |
| 3 | 1 | B Item 3 |
+----+------+----------+
3 rows in set (0.00 sec)
mysql> select * from tablec;
+----+------+----------+-------+
| id | Bid | name | value |
+----+------+----------+-------+
| 1 | 1 | C Item 1 | 10 |
| 2 | 2 | C Item 2 | 20 |
| 3 | 1 | C Item 3 | 15 |
| 4 | 2 | C Item 4 | 5 |
| 5 | 3 | C Item 5 | 12 |
+----+------+----------+-------+
5 rows in set (0.00 sec)
TableA 通过 Aid 链接到 TableB,TableC 通过 Bid 链接到 TableB。
我想要的是 tableA 的 id 和所有 TableC 项目的值的总和。
我对上面例子的期望结果集是
+-----------+--------+
| tablea.id | sum |
+-----------+--------+
| 1 | 37 |
| 2 | 25 |
+-----------+--------+
最佳答案
SELECT a.ID, SUM(c.value) totalValue
FROM tablea a
INNER JOIN tableb b
On a.ID = b.AID
INNER JOIN tablec c
ON b.ID = c.BID
GROUP BY a.ID
如果 tableA 中的
ID
可能在其他表上不存在,并且您还想显示其结果,请改用 LEFT JOIN
SELECT a.ID, COALESCE(SUM(c.value), 0) totalValue
FROM tablea a
LEFT JOIN tableb b
On a.ID = b.AID
LEFT JOIN tablec c
ON b.ID = c.BID
GROUP BY a.ID
关于php - 用于获取列总和的 SQL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13265567/