2013-11-28 66 views
0

我需要總結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 | 
+----------------+----------------+ 

任何想法如何得到這個?

+1

我認爲最好不要把''SUM''這兩個放在一起,它會給你帶來什麼好處?兩個獨立的SQL將花費更少的時間(不加入,所以它會更快),併爲您提供準確的結果。 – nrathaus

回答

1

一個可能的答案是:

SELECT (select SUM(c1.amount) from c1 where c1.a = a.id) as c1_amount, 
     (select SUM(c2.amount) from c2 where c2.a = a.id) as c2_amount 
FROM a 
WHERE a.id = 1; 

Link to SQL Fiddle

順便說一句 - 感謝把數據和創建腳本。這有很大幫助。

+0

非常感謝,這工作正常!你會如何在同一個表上添加另一個查詢,例如:我想知道c1中指向一個的entrys數。你會添加另一個子查詢,如: (從c1選擇COUNT(c1.id),其中c1.a = a.id)爲c1_count 還是有更快的方法? – Werner

0
SELECT a.* 
    , SUM(CASE WHEN b.source = 'c1' THEN amount END) c1_ttl 
    , SUM(CASE WHEN b.source = 'c2' THEN amount END) c2_ttl 
    FROM a 
    JOIN 
    ( 
     SELECT *,'c1' source FROM c1 UNION SELECT *,'c2' FROM c2 
    ) b 
    ON b.a = a.id; 
+----+--------+--------+ 
| id | c1_ttl | c2_ttl | 
+----+--------+--------+ 
| 1 | 5.00 | 1.00 | 
+----+--------+--------+ 
0

另一種解決方案。

SELECT * 
FROM 
    (SELECT SUM(c1.amount) FROM c1 WHERE c1.a = 1) C1 
INNER JOIN 
    (SELECT SUM(c2.amount) FROM c2 WHERE c2.a = 1) C2;