我正在使用 PHP 和 MYSQL 开发一个基本的社交网络。我试图在表格中显示 4 个最受欢迎的帖子。
我有两个表,表 1 是'discussions'
,表 2 是'comments'
。
表 'discussions'
有一个列 'id
',它与表 'comments'< 中的列
。因此,每当用户对讨论发表评论时,就会在“comments”表中添加一行,其中 'discid'
匹配'discid'
是讨论的 ID。我可以显示最新的评论和讨论,但无法显示 HitTest 门的讨论,因此评论最多的讨论。
因此,我需要找到一种方法,根据特定讨论 ID 在表 'comments'
的列 'discid'
中出现的次数对表讨论进行排序>.
例如:
On the discussion with id 7, there are 4 comments with discid 1.
On the discussion with id 2, there are 3 comments with discid 2.
所以我需要我的sql查询首先显示id 7,然后显示id 2,...
谁能帮我解决这个问题?将不胜感激!
最佳答案
让我知道它是否有效或者..
SELECT d.*
FROM discussions AS d
JOIN ( SELECT c.*, COUNT(c.discid) AS cnt
FROM comments AS c
GROUP BY c.discid
) AS c2 ON ( c2.discid = d.id )
ORDER BY c2.cnt DESC;
关于php - MYSQL 按其他表中出现次数最多的值对行进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33689330/