加入具有计数或总和的MYSQL

时间:2019-02-12 17:23:36

标签: mysql sql count left-join

我正在尝试执行带有联接的查询。如果我将'nil'用作numcomments,则会得到所有故事,但是如果我尝试使用COUNT来计数,则会将故事限制为仅带有注释的故事。我想要的是找回所有故事,但如果计数为零,则给零

这是架构

//stories
id|story
1|Microsoft Announces Earnings
2|Apple Inks Content Deal
3|Google In Talks With Nissan
4|Netflix Greenlights Series

//comments
id|storyid|comment
1|1|Not what I would have expected
2|1|Look at numbers for Azure
3|1|I called this
4|3|Who cares

Here is the query:
This only returns the stories with commments ie stories 1 and 3

$sql = "
SELECT COUNT(c.comment) numcomments
     , s.story event
     , s.id
     , c.storyid   
  FROM stories s
  LEFT 
  JOIN comments c
    ON c.storyid = s.id 
";

//this returns all the stories but does not give me a count of comments for obvious reasons

$sql = "
SELECT 'nil' numcomments
     , s.story event
     , s.id
     , c.storyid   
  FROM stories s
  LEFT 
  JOIN comments c
    ON c.storyid = s.id 
";

如何获取所有故事,但是如果没有评论,则在计数或numcomments字段中输入零即可

3 个答案:

答案 0 :(得分:1)

尝试以下查询:

SELECT s.id, s.story, count(c.id) as NumOfComments 
FROM stories s LEFT JOIN comments ON  s.id=c.storyid 
GROUP BY s.id, s.story

答案 1 :(得分:1)

集合函数需要group by,这在您的第一个查询中会丢失

SELECT COUNT(c.comment) as `numcomments`,s.story as event,s.id,c.storyid   
FROM `stories` s
LEFT JOIN comments `c` ON 
c.storyid = s.id  group by s.story ,s.id,c.storyid 

第二个查询您没有任何聚合count()函数,因此其正常不显示计数

答案 2 :(得分:1)

您始终需要按未汇总的列进行分组。

尝试一下

$sql = "
SELECT COUNT(c.comment) numcomments
     , s.story event
     , s.id
     , c.storyid   
  FROM stories s
  LEFT 
  JOIN comments c
   ON c.storyid = s.id 
Group by 
s.story 
     , s.id
     , c.storyid
";