如果计数为空,我如何才能得到计数为 0。当我运行以下语句时:
SELECT S.shortText, COUNT(O.selectionID) AS C FROM Opinions O
LEFT JOIN Selections S ON S.id=O.selectionID
WHERE S.qID=3 AND MONTH(O.entryDate)=5
GROUP BY S.shortText
shortText C
---------------- ----
Leisure 0 <------ this line missing
Business 3
University visit 1
我的选择表
id shortText
----- ----------------
1 Leisure
2 Business
3 University visit
我的意见表
id entryDate selectionID
----- --------------------- --------------
186 5/21/2012 11:34:37 AM 2
205 5/22/2012 9:13:25 AM 2
216 5/22/2012 9:43:14 AM 2
237 5/24/2012 8:24:00 PM 3
最佳答案
如果您想要将 Leisure 行显示为 0,即使 opinions 表中没有匹配的记录。使用子查询如下:
select t1.shorttext,if(t2.c is null,0,t2.c)as c from selections t1 left join (
SELECT s.id,S.shortText, COUNT(O.selectionID) AS C FROM selections S
LEFT JOIN opinions O ON S.id=O.selectionID
WHERE MONTH(O.entryDate)=5
GROUP BY S.shortText
) t2 on t1.id=t2.id
关于mysql - 如何加入mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12950261/