2017-02-16 49 views
0

我有兩個表,一個是「Posts」,另外一個是來自Posts的外鍵的「Comments」。 如何顯示大多數評論PHP MySQL外鍵排序

郵政表

+----+-------+--------------+ 
| Id | Name | Message  | 
+====+=======+==============+ 
| 1 | John | John's msg | 
| 2 | Marco | Marco's msg | 
| 3 | Ivan | Ivan's msg | 
+----+-------+--------------+ 

評語表的帖子,帖子ID是外鍵

+----+-------+--------------+--------+ 
| Id | Name | Comment  | PostId | 
+====+=======+==============+========+ 
| 1 | John | John's msg | 2  | 
| 2 |Joseph |Joseph's msg | 2  | 
| 3 | Ivan | Ivan's msg | 2  | 
| 4 |Natalie|Natalie's msg | 1  | 
+----+-------+--------------+--------+ 

在前端頁面上的帖子會被標識2進行排序,因爲它有最意見,然後是1,並且發佈id 2作爲最後。

解決方案THX到GurV:

select p.*, 
    (
     select count(*) cnt 
     from comments c 
     where c.postid = p.id 
     ) cnt 
from posts p 
order by cnt desc; 
+4

加油後需要按Post.Id。嘗試一下。 – Strawberry

+1

您是否真的嘗試過任何東西或只是來這裏快速回答? – Option

回答

2

你可以找到的意見計數的子查詢每個職位與職位表連接它來執行對發現的數排序:

select p.* 
from posts p 
left join (
    select postid, count(*) cnt from 
    comments 
    group by postid 
) c on p.id = c.postid 
order by c.cnt desc; 

如果您要獲取所有帖子,那麼上面的內容會盡可能最快。

如果它將用於幾篇文章,您可以使用相關查詢來查找計數,然後按它進行排序。

select p.*, 
    (
     select count(*) cnt 
     from comments c 
     where c.postid = p.id 
     ) cnt 
from posts p 
order by cnt desc; 
+0

如果表變得非常大,會發生什麼?這可能會降低性能 – Energizem

+1

@Energizem - 更新了更多詳細信息和備用解決方案 – GurV

+0

第一個解決方案僅顯示包含1條或更多評論的帖子,未選中包含0條評論的帖子。 第二個解決方案按預期工作,謝謝 – Energizem

1

你會加入

SELECT Post.Id, Post.Name, Post.Message, 
SUM(CASE WHEN Comment.Id IS NOT NULL THEN 1 END) as Comments 
FROM Post 
LEFT JOIN Comment ON Post.Id = PostId 
GROUP BY Post.Id, Post.Name, Post.Message 
ORDER BY Comments DESC 
+1

@Energizem我會修改使用'LEFT JOIN',這應該可以做到。 – wogsland