MySQL - 连接三个表以获得列的SUM

时间:2017-02-22 09:18:26

标签: mysql

我有一个有3个表的数据库。第一个表托管用户ID和位置。第二个表主持boss / squire id。第三个主持乡绅身份和钱。假设我是table1.id = 1。我是一个带有2个乡绅的pos1,带有pos1的table1.id = 2和带有pos1的table1.id = 3,其中2个在他们下面有乡绅。 table1.id = 4,pos2和table1.id = 5,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

我希望结果是

sumTotal = 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

帮助了解请点击:http://sqlfiddle.com/#!9/e8924/4/0

1 个答案:

答案 0 :(得分: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

Demo here

修改

如果您还想在查询中加入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