表格
id title category
<小时/>
1 hello1 1
2 hello2 2
3 hello3 1
查询
select *
from videos
where category in
(
select category
from videos
group by
category
having
count(*) < 3
ORDER BY RAND()
)
我的目标是以随机顺序从每个类别中获得 2 个标题 我也想以这种方式获取记录
category1
title1
title2
<小时/>
category2
title1
title2
最佳答案
以下查询给出每个类别中不超过两个随机行:
SELECT title, category
FROM (
SELECT v.*,
if( category = @last_cat,
if( @last_cat:=category, @x:=@x+1,@x:=@x+1),
if( @last_cat:=category, @x:=0,@x:=0)
) x
FROM (SELECT @last_cat:=-9876, @x:=-91234) x,
(SELECT * FROM videos ORDER BY category, rand()) v
) x
WHERE x < 2
关于php - MySQL 按类别分组,每个类别限制 N 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27752407/