在downvoting之前,请看看我的问题。
我正在撰写我的文章网站。我的网站上有一节显示热门文章。热门文章基于喜欢和评论。我使用下面的查询来显示热门文章:
select
s.id as story_id,
s.title as story_title,
COUNT(l.id) as total_likes,
COUNT(cm.id) as total_comments
from
stories s
right outer join
likes l
on
s.id = l.type_id
right outer join
comments cm
on
cm.story_id = s.id
group by s.id
order by total_likes desc,total_comments desc
我收到的热门文章却只有5篇。文章正在展示,但只有5篇,我想要的文章没有喜欢或评论后的最后一篇这里是截图
在这里,您可以观察到只有至少有1个喜欢或评论的文章。我想收到没有喜欢或评论的文章
任何人都可以解决我的问题,提前谢谢?
答案 0 :(得分:2)
这也将返回没有喜欢或评论的故事(你应该使用左连接):
select
s.id as story_id,
s.title as story_title,
COUNT(l.id) as total_likes,
COUNT(cm.id) as total_comments
from stories s
left join likes l on s.id = l.type_id
left join comments cm on cm.story_id = s.id
group by s.id, s.title
order by total_likes desc,total_comments desc
答案 1 :(得分:2)
你必须使用左连接。这应该有效:
select
s.*,
COUNT(l.id) as total_likes,
COUNT(cm.id) as total_comments
from stories articles
left join likes l on articles.id = l.type_id
left join comments cm on cm.story_id = s.id
group by articles.id, articles.title
order by total_likes desc,total_comments desc
希望有所帮助