我有一个包含 3 个表的数据库。第一个表包含用户 ID 和职位。第二张表托管老板/乡绅 ID。第三层存放乡绅 ID 及其金钱。假设我是table1.id=1。我是一个 pos1,有 2 个乡绅,table1.id=2 有 pos1,table1.id=3 有 pos1,在这 2 个下面有乡绅。 table1.id=4 with pos2 和table1.id=5 with pos3 都在table1.id=2 下。与 table1.id=3 相同。
table1.id=1 ------> table1.id=2 ------> table1.id=4
| |
| |
| ------> table1.id=5
|
------> table1.id=3 ------> table1.id=6
|
|
------> table1.id=7
我想要的结果是
总计 = 1000
CREATE TABLE Table1 (`id` INT, `pos` VARCHAR(255))
CREATE TABLE Table2 (`id` INT, `id_boss` INT, `id_squire` INT)
CREATE TABLE Table3 (`id` INT, `id_squire` INT, `money` INT)
INSERT INTO Table1 (`id`, `pos`)
VALUES
(1, 'pos1'),
(2, 'pos1'),
(3, 'pos1'),
(4, 'pos2'),
(5, 'pos2'),
(6, 'pos3'),
(7, 'pos3');
INSERT INTO Table2 (`id`, `id_boss`, `id_squire`)
VALUES
(1, 1, 2),
(2, 1, 3),
(4, 2, 4),
(5, 2, 5),
(6, 3, 6),
(7, 3, 7);
INSERT INTO Table3 (`id`, `id_squire`, `money`)
VALUES
(1, 4, 100),
(2, 5, 200),
(3, 6, 300),
(4, 7, 400);
我将使用 table1.id=1
最佳答案
您首先需要自连接到 Table2
以便获得后代节点:
SELECT SUM(money)
FROM Table2 AS t21
JOIN Table2 AS t22 ON t21.id_squire = t22.id_boss
JOIN Table3 AS t3 ON t22.id_squire = t3.id_squire
WHERE t21.id_boss = 1
编辑:
如果您还想在查询中包含 Table1
,那么您可以将它放在 JOIN
链的开头:
SELECT SUM(t3.money)
FROM Table1 AS t1
JOIN Table2 AS t21 ON t1.id = t21.id_boss
JOIN Table2 AS t22 ON t21.id_squire = t22.id_boss
JOIN Table3 AS t3 ON t22.id_squire = t3.id_squire
WHERE t1.id = 1
关于MySQL - 连接三个表以获得列的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42387274/