给定两个具有公共id和整数值的表:
table1: table2:
| id | val | | id | val |
+------+------+ +------+------+
| 1 | 0 | | 1 | 1 |
| 2 | 1 | | 1 | 1 |
| 3 | 1 | | 2 | 2 |
| 4 | 2 | | 2 | 2 |
| 5 | 2 | | 3 | 2 |
| 3 | 2 |
| 3 | 2 |
| 4 | 6 | <id shifted for readability>
如何在一个查询中存档此结果:
result-table:
| id | val |
+------+------+
| 1 | 2 |
| 2 | 5 |
| 3 | 7 |
| 4 | 8 |
| 5 | 2 |
修改
我得到了一些答案:
SELECT t1.id, t1.val + SUM(t2.val) AS val
FROM table1 t1
LEFT JOIN table2 t2 ON (t1.id = t2.id)
GROUP BY t1.id
是什么让我:
id val
1 2
2 5
3 7
4 8
5 NULL
但是2 plus nothing = 2
而不是NULL
。有不同的方式吗?
答案 0 :(得分:2)
您忘了group by
:
SELECT t1.id, t1.val - SUM(t2.val) AS val
FROM t1
JOIN table2 t2 ON (t1.id = t2.id)
GROUP BY t1.id
当然,我不确定您为什么要尝试减去示例查询中的值。也许你的意思是+
?
答案 1 :(得分:0)
使用union而不是join:
select id, sum(val)
(
SELECT t1.id, t1.val as val
FROM table1 t1
union all # note this change to include all the value from 2 table
select t2.id, t2.val as val
from table2 t2
) as unionTable
groupby id;