我有一个id值表,需要计算每个id出现在另一个表的列中的次数。
我已经想出了如何只针对至少出现一次的值:
SELECT one.id, COUNT(*) FROM table1 one, table2 two WHERE one.id = two.id GROUP BY one.id;
但无法弄清楚如何同时包含首先出现但不会出现在第二个表格中的ID。
示例:
table1: table2:
+-----+ +-----+
| id | | id |
+-----+ +-----+
| 11 | | 11 |
| 12 | | 12 |
| 13 | | 14 |
| 14 | | 11 |
+-----+ | 11 |
| 12 |
+-----+
结果将是:
+-----+----------+
| id | count(*) |
+-----+----------+
| 11 | 3 |
| 12 | 2 |
| 14 | 1 |
+-----+----------+
我试图让它也包括行| 13 | 0 |
答案 0 :(得分:1)
您正在进行隐式内部联接,不鼓励这样做。相反,您需要的是左连接,例如:
SELECT one.id, COUNT(two.id)
FROM table1 one LEFT JOIN table2 two
ON one.id = two.id
GROUP BY one.id;