3

我有三个相互链接的表。

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 |
+-----------+--------+
4

3 回答 3

10
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

如果ID其他表上可能不存在 from tableA 并且您还想显示它们的结果,请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
于 2012-11-07T08:13:40.703 回答
3
SELECT a.id, SUM(c.value) sum
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

SQL 小提琴演示

于 2012-11-07T08:13:17.537 回答
3

你可以试试这个查询

SELECT a.id AS A, SUM(c.value) AS SUM 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;
于 2012-11-07T08:32:41.757 回答