我有类似的查询。
SELECT t.* FROM
(SELECT
`user_bookmarks`.`id` AS `user_bookmark_id`,
`bookmark_id`,
`user_bookmarks`.`user_id`,
`bookmark_url`,
`bookmark_website`,
`bookmark_title`,
`bookmark_preview_image`,
`bookmark_popularity`,
`category_id`,
`category_name`,
`pdf_txt_flag`,
`youtube_video`,
`content_preview`,
`snapshot_preview_image`,
`mode` ,
@r:= CASE WHEN category_id = @g THEN @r+1 ELSE @r:=1 END `rank` ,
@g:=category_id
FROM
`user_bookmarks`
LEFT JOIN `bookmarks`
ON `user_bookmarks`.`bookmark_id` = `bookmarks`.`id`
LEFT JOIN `categories`
ON `user_bookmarks`.`category_id` = `categories`.`id`
JOIN (SELECT @r:=0,@g:=0) t1
WHERE `category_id` IN (164, 170, 172)
ORDER BY category_id
) t
WHERE t.rank <=6
它是指这个答案。 This is link
我们可以在上面的查询中计算每个 Category_id 的结果总数。我们可以在mysql本身中完成它。
谢谢。
答案 0 :(得分:2)
你可以通过一些技巧来做到这一点:
select t.*
from (select t.*,
@r := (CASE WHEN category_id = @g THEN @r ELSE rank END) as maxrank,
@g := category_id
from (<inner query here>) t
order by category_id, t.rank desc
) t
where t.rank <= 6;
我们的想法是对数据进行重新排序,然后在每个类别的行中复制排名。