【问题标题】:Mysql - show all results, including 0 resultsMysql - 显示所有结果,包括 0 个结果
【发布时间】:2013-10-21 12:31:15
【问题描述】:

所以我有以下表格:

文章

  • article_id

评论

  • comment_id
  • article_id

我想要做的是搜索所有文章,无论是否有 cmets,并显示文章 id 以及它有多少 cmets。

假设我有两篇文章,只有第一篇有 cmets。我无法查询显示他们俩和他们的 cmets 号码。

编辑 1:

阅读回复后,我提出了以下查询,我就快到了!只有一个问题。当一篇文章没有 cmets 时,我得到 1,而不是得到 0。

SELECT *,COUNT(a.article_id) FROM article as a LEFT JOIN comment as c ON a.article_id = c.article_id GROUP BY a.article_id;

编辑 2:

一个简单的错误。我将“COUNT(a.article_id)”更改为“COUNT(C.article_id)”。太明显了! :) 感谢人们的帮助;)

SELECT *,COUNT(c.article_id) FROM article as a LEFT JOIN comment as c ON a.article_id = c.article_id GROUP BY a.article_id;

【问题讨论】:

  • 使用左连接。应该工作。
  • 我不知道如何使用 LEFT JOIN :/ 我已经尝试过使用它但我总是遇到一些错误... :(

标签: mysql zero


【解决方案1】:

试试这个:

SELECT * FROM Article as a INNER JOIN Comment as c ON a.article_id = c.article_id;

【讨论】:

  • 我将此标记为正确,因为它的答案更接近我想要的 :) 我只需要进行一些更改。谢谢!
【解决方案2】:

你想要

SELECT 
    IFNULL(COUNT(c.comment_id),0) AS 'Comment Count' , 
    a.article_id 
FROM 
  article a 
LEFT JOIN 
  comment c 
  ON c.article_id

我在这里所做的是使用 MySQL 的 LEFT JOIN 将评论表与文章表(我们的参考)进行比较。在c.article_ida.article_id 之间存在匹配的地方,我们获取数据。

【讨论】:

  • Count 永远不会返回NULL,如果没有找到行,它将返回 0
【解决方案3】:

试试LEFT JOIN

Select 
article_id, 
count(comment_id)
from 
article a
LEFT JOIN comment c on (a.article_id=c.article_id)
GROUP BY article_id

【讨论】:

    猜你喜欢
    • 2019-07-02
    • 2015-12-15
    • 1970-01-01
    • 1970-01-01
    • 2012-04-08
    • 2015-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多