MySql:来自不同表的JOIN和SUM

时间:2013-11-28 14:45:34

标签: mysql sql distinct

我需要将n:1中连接的2个表(c1,c2)中的金额总结为表a。问题是:如果我只能在一个查询中完成它会更好,因为实际情况有点复杂;-)我把它带到了这个测试用例:

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

知道怎么做到这个吗?

3 个答案:

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

BTW - 感谢您输入数据并创建脚本。这有很大帮助。

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

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