1

如果它为空,我怎样才能得到计数为 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   
4

3 回答 3

2

如果您想将休闲行显示为 0,即使意见表中没有匹配的记录。使用子查询如下:

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

http://sqlfiddle.com/#!2/8ca3e/11

于 2012-10-18T08:45:29.250 回答
1

如果要显示,请交换SelectionsandOpinions表。

SELECT S.shortText, COUNT(O.selectionID) AS C 
FROM   Selections S
       LEFT JOIN Opinions O 
         ON S.id=O.selectionID
-- WHERE  S.ID=3 AND                     -- add extra conditions here
--       MONTH(O.entryDate)=5 
GROUP BY S.shortText

SQLFiddle 演示

或使用RIGHT JOIN

SELECT S.shortText, COUNT(O.selectionID) AS C 
FROM   Opinions O 
       RIGHT JOIN Selections S
         ON S.id=O.selectionID
-- WHERE  S.ID=3 AND 
--       MONTH(O.entryDate)=5 
GROUP BY S.shortText

SQLFiddle 演示

于 2012-10-18T08:30:04.450 回答
0

你试过换桌子吗?从 SELECTTIONS 中选择并加入 OPINIONS,而不是您拥有它的方式。

于 2012-10-18T08:38:44.890 回答