我想根据类别ID从数据库中检索最后三个帖子,例如
post_id category_id
1 1
2 4
3 3
4 4
5 2
6 1
7 3
8 2
9 4
10 1
11 2
12 3
我想要回复像这样的东西
post_id category_id
1 1
6 1
10 1
5 2
8 2
11 2
7 3
3 3
12 3
4 4
2 4
9 4
我已经提出了这个问题,但是如何限制每个category_id返回3个?
SELECT
`posts`.`id`,
`posts`.`title`,
`posts`.`slug`,
`posts`.`image`,
`posts`.`status`
FROM
`posts`
ORDER BY
`posts`.`id`
如何限制为每个category_id返回3条记录,当我使用LIMIT 3查询时只返回3条记录。
答案 0 :(得分:1)
您可以从每个category_id
中读取3个新的post_idSELECT
p1.`post_id`,
p1.`category_id`
FROM
post p1
JOIN post p2 ON p1.`category_id` = p2.`category_id`
AND p2.`post_id` >= p1.`post_id`
GROUP BY
p1.`post_id`,
p1.`category_id`
HAVING
COUNT(*) <= 3
ORDER BY
`category_id`,
`post_id`
SQL FIDDLE:LIVE DE
答案 1 :(得分:-2)
$sql = "SELECT `posts`.* FROM `posts` WHERE `posts`.`category_id` = 1 ORDER BY `posts`.`id` DESC LIMIT 3"
然后运行
$sql = "SELECT `posts`.* FROM `posts` WHERE `posts`.`category_id` = 2 ORDER BY `posts`.`id` DESC LIMIT 3"
然后运行
$sql = "SELECT `posts`.* FROM `posts` WHERE `posts`.`category_id` = 3 ORDER BY `posts`.`id` DESC LIMIT 3"
然后那个,但别忘了
$sql = "SELECT `posts`.* FROM `posts` WHERE `posts`.`category_id` = 4 ORDER BY `posts`.`id` DESC LIMIT 3"`
然后你已到达目的地
最好只分开运行查询。