MySQL按多个ID选择记录,每个ID有LIMIT


MySQL Selecting records by multiple IDs with LIMIT per each ID

我的MySQLi查询被卡住了。场景如下:-我需要为每个帖子选择最多10条评论。-我正在使用此查询,但它不能按我需要的方式工作-Post ID在阵列中

$comments_query = mysqli_query($con, "SELECT * FROM comments WHERE pid IN ({$decodedPostIds}) AND state='1' order by time LIMIT 10");
  • LIMIT 10适用于整体评论

提前感谢您的建议和回答。Ps.我为我的英语感到抱歉。Peter

LIMIT 10

表示结果将包含来自HOLL查询输出的10行。

假设在数据库中有两个帖子:post1包含5个相关评论,post2包含10个相关评论。

执行所述查询:SELECT * FROM comments WHERE pid IN ({$decodedPostIds}) AND state='1' order by time

将返回:

  • post1:评论1
  • post1:评论2
  • 帖子1:评论3
  • 帖子1:评论4
  • 帖子1:评论5
  • post2:评论1
  • post2:评论2
  • 帖子2:评论3
  • 帖子2:评论4
  • 帖子2:评论5
  • 帖子2:评论6
  • 帖子2:评论7
  • 帖子2:评论8
  • 帖子2:评论9
  • post2:评论10

现在,将LIMIT 10添加到查询中,将返回孔结果的前10行,即从post1:comment1post2:comment5

您有两个解决方案:

  1. 为每个帖子做一个循环,并在该帖子上执行您的查询:

    从注释中选择*,其中pid=$post_idAND state="1"order by time LIMIT 10

  2. 获取所有帖子,并使用PHP代码,将每个帖子的前10个评论分组

伪代码:

$rows = mysqli_query($con,'SELECT * FROM comments WHERE WHERE pid IN ({$decodedPostIds}) AND state='1' order by time LIMIT 10');
foreach($rows as $row){
    if(count($arr[$row['post_id']]) < 10){
        array_push($arr[$row['post_id']],$row)
    }
}

现在$arr是数组,其中每个键都是post_id,其值为第10个注释。

IMO:我更喜欢解决方案2(不喜欢在循环中执行查询)。

希望能有所帮助。