【问题标题】:Select posts with most comments combined with child and parent posts选择评论最多的帖子以及子帖子和父帖子
【发布时间】:2014-01-21 19:54:17
【问题描述】:

我设置了两个 MySQLi 表。一种叫做“AIW_cmets”。它有一个标题为“post_id”的列,让我知道这条评论指的是什么帖子。

我还有一个名为“AIW_posts”的表格,用于保存所有帖子。

现在我需要一个 mysqli 选择语句来首先检索具有最多 cmets 的帖子。我使用以下代码使代码按预期完美运行:

$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 和给定任何帖子的 id 的父帖子的数组。

我如何像以前一样选择具有最多 cmets 的帖子,但这次包括所有父和子帖子 cmets,就好像它们是同一个帖子一样?

【问题讨论】:

  • 肯定有一种方法可以使用您建议的结构来做到这一点,但是您是否研究过嵌套集结构?这使得在 SQL 中使用分层数据更容易。这是examples 中的couple。

标签: php mysql sql select mysqli


【解决方案1】:

下面是返回您要查找的数据的 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 实现,以便专注于您的问题并简化我的答案的可读性。

关于我的查询的一些信息:

  • 而不是使用老式语法来连接关节(...FROM table1, table2 WHERE...),我使用了INNER JOINclause
  • 我使用了另外两个 获取父子帖子的关节
  • 出于可读性目的, 我的查询只返回post_id。要获得您想要的所有列,您 只需将它们添加到 SELECT 子句中,不要忘记 在GROUP BY 子句中添加这些列!

希望这会对你有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-19
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 2019-05-23
    相关资源
    最近更新 更多