2017-02-22 141 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請檢查我所做的修改。 –