我设置了两个MySQLi表。其中一个叫做"AIW_comments“。它有一个标题为"post_id“的专栏,让我知道这条评论指的是什么帖子。
我还有一个名为"AIW_posts“的表,里面有所有的帖子。
现在,我需要一条mysqli select语句来首先检索评论最多的帖子。我使用以下命令让代码完全按照预期运行:
$results = mysqli_query($con,"SELECT AIW_posts.*
FROM AIW_comments, AIW_posts
WHERE (AIW_posts.id = AIW_comments.post_id AND childPost_id = 0)
GROUP BY AIW_comments.post_id
ORDER BY COUNT(*) DESC
, AIW_comments.post_id DESC
LIMIT $startIndex,$amount") or die(mysqli_error($con));
}我添加了编辑帖子的功能。我为"AIW_posts“添加了两个新列"parentPost_id”和"childPost_id“。我创建了一个PHP函数,它为我提供了一个包含每个子帖子的id的数组,以及给定任何post的id的父post。
我如何选择评论最多的帖子,就像我之前做的那样,但这一次包括所有父子帖子的评论,就好像它们是同一篇帖子一样?
发布于 2014-09-03 17:28:09
下面是将返回您要查找的数据的SQL查询:
SELECT P.post_id
FROM AIW_posts P
INNER JOIN AIW_comments C ON C.post_id = P.post_id
INNER JOIN AIW_posts PP ON PP.post_id = P.parentPost_id
INNER JOIN AIW_posts PC ON PC.post_id = P.childPost_id
GROUP BY P.post_id
ORDER BY COUNT(C.post_id) DESC, P.post_id DESC
LIMIT 1 -- Or whatever limit you want我选择只向您提供SQL查询,而不是PHP实现,以便关注您的问题并简化我的答案的可读性。
以下是关于我的查询的几个信息:
INNER JOINclausepost_id。要获得所需的所有列,只需将它们添加到SELECT子句中,不要忘记在中添加这些列希望这能对你有所帮助。
https://stackoverflow.com/questions/21267746
复制相似问题