我有三个表,tableA(id,A),tableB(id,B)和tableC(id,C)。 id是唯一的主键。现在我想对这三个表运行一个查询,找出每个id的A,B和C值的总和。 (即如果在表A中存在id 1但在表B中不存在,则对于id 1,值B应被视为0).example:tableA:
id A
1 5
2 6
3 2
5 7
tableB的:
id B
2 5
3 8
4 1
表C:
id C
5 2
输出应为:
id Sum
1 (5 + 0 + 0 =)5
2 (6 + 5 + 0 =)11
3 (2 + 8 + 0 =)10
4 (0 + 1 + 0 =)1
5 (7 + 0 + 2 =)9
答案 0 :(得分:1)
首先获取ID的不同列表( UNION ),以便包含all,然后LEFT JOIN将值一起添加。
像
这样的东西SELECT IDs.ID,
IFNULL(tableA.A,0) + IFNULL(tableB.B,0) + IFNULL(tableC.C,0) SumVal
FROM (
SELECT ID
FROM tableA
UNION
SELECT ID
FROM tableB
UNION
SELECT ID
FROM tableC
) IDs LEFT JOIN
tableA ON IDs.ID = tableA.ID LEFT JOIN
tableB ON IDs.ID = tableB.ID LEFT JOIN
tableC ON IDs.ID = tableC.ID
答案 1 :(得分:1)
这样的事情应该有效:
select id, sum(val) from
( select id, "A" as val from "tableA"
union all
select id, "B" as val from "tableB"
union all
select id, "C" as val from "tableC" ) as joined
group by id
order by id
答案 2 :(得分:1)
我无法使用MySql对其进行测试,但这适用于我的数据库(HSQLDB,Oracle):
select ID, sum(X) from
(SELECT ID, A as X FROM tableA
UNION
SELECT ID, B as X FROM tableB
UNION
SELECT ID, C as X FROM tableC)
group by ID
答案 3 :(得分:1)
不确定MySQL的确切语法,但这适用于SQL Server:
SELECT ID, SUM(ColToSum) As SumValue FROM
(
SELECT ID, A As ColToSum FROM TableA
UNION ALL
SELECT ID, B As ColToSum FROM TableB
UNION ALL
SELECT ID, C As ColToSum FROM TableC
) Combined
GROUP BY ID
请记住使用“UNION ALL”,而不仅仅是“UNION”,它会在结合时删除重复的行(请参阅http://dev.mysql.com/doc/refman/5.0/en/union.html)