2017-03-16 66 views
1

在downvoting之前,看看我的問題。Mysql查詢不返回沒有喜歡或沒有評論的文章

我正在我的文章網站上工作。我的網站上有一個部分顯示流行文章。流行文章基於喜歡和評論。我使用下面的查詢顯示熱門文章:

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個,我想最後一次在此之後沒有喜歡或評論文章是截圖

enter image description here

在這裏,你可以觀察到的唯一的文章顯示了誰擁有至少1狀或評論。我想得到沒有喜歡或評論的文章

任何人都可以解決我的問題,在此先感謝?

回答

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 
+0

謝謝你,讓我看看 –

+0

它的工作原理感謝@scaisEdge。 –

+0

@Ilyaskarim好,如果我的回答是正確的,請將其標記爲已接受...看到這裏如何 http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – scaisEdge

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 

希望它可以幫助