从LEFT JOIN获取行数

时间:2015-01-12 19:55:08

标签: mysql sql

博客表

T

评论表

Comment table

我试图在一个博客上没有评论评论,如果没有评论,他们会返回0.我尝试了很多加入,但我没有得到正确的数据。

我的查询 -

SELECT count(cid),     tbl_blog.blog_name,tbl_blog.bid,tbl_blog.blog_images,tbl_blog.blog_content,tbl_blog.created_date
    FROM tbl_blog
     LEFT JOIN tbl_blog_comment
    ON tbl_blog_comment.bid = tbl_blog.bid

请帮忙。

1 个答案:

答案 0 :(得分:1)

Count(cid)需要是count(TABLE.COLUMN)格式。

所以试试:

count(tbl_blog_comment.cid) as countRows

这是因为查询正在多个表上运行但是 - 据我所知你的问题 - 计数只是一个列,但不告诉MySQL列在哪里。

编辑:这是更新以反映评论对话并提供更全面的答案:

SELECT tbl_blog.blog_name, tbl_blog.bid, tbl_blog.blog_images, tbl_blog.blog_content, tbl_blog.created_date, COUNT(tbl_blog_comment.cid) as CountComments
    FROM tbl_blog
     LEFT JOIN tbl_blog_comment
    ON tbl_blog_comment.bid = tbl_blog.bid GROUP BY tbl_blog.bid

这将返回每个博客的评论计数,对于结果集的每一行,每行对应一个博客。计数将在数组变量“CountComments”

中返回

同样归功于Mihai的“Group By”补充。

相关问题