SQL:获取所有评论的所有帖子(包括0)

时间:2012-12-07 20:31:39

标签: sql

此刻我有这个疑问:

select p.idpost, count(c.idpost)
from posts p join comments c on p.idpost = c.idpost
group by p.idpost

结果仅显示包含评论的帖子。我怎样才能获得所有帖子?

2 个答案:

答案 0 :(得分:0)

使用left join代替join

select p.idpost, count(c.idpost)
from posts p 
    left join comments c on p.idpost = c.idpost
group by p.idpost

Here is a good visual explanation of SQL joins with code它显示每次加入会发生什么

答案 1 :(得分:0)

使用LEFT JOIN:

select
    p.idpost,
    count(c.idpost)
from posts p
LEFT join comments c on p.idpost = c.idpost
group by p.idpost

干杯