给出了两个具有共同 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
。有不同的方法吗?