我有两张桌子。我想从表1中选择ID,并从表2中进行计数
表格1
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子句中使用带有附加条件的左连接,即and a.qId =30
如果未找到left 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
样本数据集更新后进行编辑
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句