您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息
三六零分类信息网 > 绥化分类信息网,免费分类信息发布

用group by 不符合条件他不返回数据,该怎么解决

2024/4/27 21:55:19发布5次查看
用group by 不符合条件他不返回数据
如:posts帖子表
create table posts(
posts_id,
forumid, (论坛id)
posts_title,
posts_posttime,
)
comments评论表
create table comments( 
comments_id,
postsid,
comments_content,
comments_posttime,
 )
我要的结果是:读出论坛id为1的所有帖子,并统计每个帖子的评论总数.
我用count(comments_id) as commentsnum 统计评论,但帖子在评论表没有评论,group by 就忽略了
posts_id  forumid   commentsnum
 1           1         4
 2           1         5
 3           1         4
 4           1         0
我要当帖子在评论表里没有评论的时候,返回0,或者返回null也行啊,怎么弄
分享到: 更多
------解决方案--------------------
select a.posts_id,a.forumid,count(b.comments_id) as commentsnum
from posts a left join comments b on a.posts_id=b.postsid
group by b.postsid having a.forumid=1

绥化分类信息网,免费分类信息发布

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录