2017-02-22 29 views
2

我有一个拥有3个表的数据库。第一个表格包含用户标识和位置。第二张桌上有老板/乡绅ID。第三名主持乡绅身份证及其金钱。假设我是table1.id = 1。我是一个pos1,有两个乡绅,table1.id = 2,pos1和table1.id = 3,pos1在这里,在这里有两个乡绅。 table1.id = 4与pos2和table1.id = 5与pos3是在table1.id = 2之下。与table1.id = 3相同。MySQL - 连接三个表以获得列的总和

table1.id=1 ------> table1.id=2 ------> table1.id=4 
      |     | 
      |     | 
      |     ------> table1.id=5 
      | 
      ------> table1.id=3 ------> table1.id=6 
           | 
           | 
           ------> table1.id=7 

我想要的结果是,我将使用table1.id

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); 

= 1

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

回答

1

你首先需要自己加入Table2,这样你才能得到des圣达特节点:

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

让我检查先生,谢谢 – Maki

+0

嗨,代码是好的,但我想用ta ble1.id = 1在WHERE。我的理由是我在table1中有其他过滤器,我没有发布,只是为了使问题更容易解释。像table1.pos = pos2类似的东西。 THanks – Maki

+0

@Maki请检查我所做的修改。 –