我需要總結2個表(c1,c2)中鏈接到表a的數量。問題是:這將是馬麗娟,如果我能在短短1個查詢做到這一點,因爲真實的情況是一個比較複雜一點;-)我把它歸結爲這個測試用例:MySql:來自不同表格的JOIN和SUM
create table a (
`id` int(10) unsigned NOT NULL, KEY(id)
) ENGINE=InnoDB;
create table c1 (
`id` int(10) unsigned NOT NULL, KEY(id),
`a` int(10),
`amount` decimal(15,2) NOT NULL
) ENGINE=InnoDB;
create table c2 (
`id` int(10) unsigned NOT NULL, KEY(id),
`a` int(10),
`amount` decimal(15,2) NOT NULL
) ENGINE=InnoDB;
INSERT INTO a SET id=1;
INSERT INTO c1 SET a=1, amount = 2;
INSERT INTO c1 SET a=1, amount = 3;
INSERT INTO c2 SET a=1, amount = 1;
SELECT SUM(c1.amount), SUM(c2.amount)
FROM a
LEFT JOIN c1 ON c1.a = a.id
LEFT JOIN c2 ON c2.a = a.id
WHERE a.id = 1;
結果當然是:
+----------------+----------------+
| SUM(c1.amount) | SUM(c2.amount) |
+----------------+----------------+
| 5.00 | 2.00 |
+----------------+----------------+
因爲c1連接了兩次並使c2中的音量加倍。但我需要得到:
+----------------+----------------+
| SUM(c1.amount) | SUM(c2.amount) |
+----------------+----------------+
| 5.00 | 1.00 |
+----------------+----------------+
任何想法如何得到這個?
我認爲最好不要把''SUM''這兩個放在一起,它會給你帶來什麼好處?兩個獨立的SQL將花費更少的時間(不加入,所以它會更快),併爲您提供準確的結果。 – nrathaus