MySQL 按多个 ID 选择记录,每个 ID 有 LIMIT 个
MySQL Selecting records by multiple IDs with LIMIT per each ID
我受困于 MySQLi 查询。场景是这样的:
- 我需要 select 每个 post 最多 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。我为我的英语感到抱歉。
彼得
LIMIT 10
表示结果将包含 HOLE 查询输出中的 10 行。
假设在数据库中您有 2 个 posts:post1 包含 5 个相关评论,post2 包含 10 个相关评论。
正在执行查询:
SELECT * FROM comments WHERE pid IN ({$decodedPostIds}) AND state='1' order by time
将return:
- post1:评论1
- post1:评论2
- post1:评论3
- post1:评论4
- post1:评论5
- post2:评论1
- post2:评论2
- post2:评论3
- post2:评论4
- post2:评论5
- post2:评论6
- post2:评论7
- post2:评论8
- post2:评论9
- post2:评论10
现在,添加LIMIT 10
查询,将return洞结果的前10行,意思是从post1:comment1 至 post2:评论 5
您有 2 个解决方案:
为每个 post 创建一个循环并在 post 上执行查询:
SELECT * 来自评论 WHERE pid = $post_id AND state='1' order by time LIMIT 10
获取所有 posts 并使用 PHP 代码,将每个 post
[=62 的前 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(讨厌在循环中执行查询)。
希望对您有所帮助。
我受困于 MySQLi 查询。场景是这样的: - 我需要 select 每个 post 最多 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。我为我的英语感到抱歉。 彼得
LIMIT 10
表示结果将包含 HOLE 查询输出中的 10 行。
假设在数据库中您有 2 个 posts:post1 包含 5 个相关评论,post2 包含 10 个相关评论。
正在执行查询:
SELECT * FROM comments WHERE pid IN ({$decodedPostIds}) AND state='1' order by time
将return:
- post1:评论1
- post1:评论2
- post1:评论3
- post1:评论4
- post1:评论5
- post2:评论1
- post2:评论2
- post2:评论3
- post2:评论4
- post2:评论5
- post2:评论6
- post2:评论7
- post2:评论8
- post2:评论9
- post2:评论10
现在,添加LIMIT 10
查询,将return洞结果的前10行,意思是从post1:comment1 至 post2:评论 5
您有 2 个解决方案:
为每个 post 创建一个循环并在 post 上执行查询:
SELECT * 来自评论 WHERE pid = $post_id AND state='1' order by time LIMIT 10
获取所有 posts 并使用 PHP 代码,将每个 post
[=62 的前 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(讨厌在循环中执行查询)。
希望对您有所帮助。