我有兩個表,一個是「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;
加油後需要按Post.Id。嘗試一下。 – Strawberry
您是否真的嘗試過任何東西或只是來這裏快速回答? – Option