我有两张 table 。我想从表 1 中选择 id,并从表 2 中计数相同
表一
Id qId opt
1 30 Chris Christie
2 30 Hillary Clinton
3 30 Allan West
4 30 Joe Biden
5 31 Mark
6 31 Ben Johnson
表2
poll_id qId ansId
201 30 1
202 30 2
204 31 8
我试过以下查询,因为表 2 中没有 3 和 4,所以只输出 ansId 1 和 2。
SELECT a.Id,
a.opt,
COUNT(b.ansId)
from Table1 a
INNER JOIN Table2 b ON a.Id = b.ansId
where a.qId =30
但我需要所有 ansId 1、2、3、4,计数为 3 和 4 为 0,如下所示。
Id opt COUNT(b.ansId)
1 Chris Christie 1
2 Hillary Clinton 1
3 Allan West 0
4 Joe Biden 0
最佳答案
首先,您缺少 group by ,count 是一个聚合函数,需要对其进行分组,其次,您需要在 on 子句中使用 left join 和附加条件,即 和 a.qId =30
因此,如果在右表中找不到左 id,它仍然会为您提供结果,使用 where 子句将过滤掉整个结果集,而如果您在连接中使用附加条件,则只会过滤右表中的记录
SELECT a.Id,
a.opt,
COUNT(b.ansId) from Table1 a
LEFT JOIN Table2 b ON a.Id = b.ansId and a.qId =30
GROUP BY a.Id
Fiddle Demo
在示例数据集更新后编辑
SELECT a.Id,
a.opt,
COUNT(b.ansId) from Table1 a
LEFT JOIN Table2 b ON a.Id = b.ansId
WHERE a.qId =30
GROUP BY a.Id
Fiddle demo 2
关于Mysql select id from table1 和 select count(id) from table2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23396951/