MySQL 按类别分组,每个类别限制 N 个
MySQL Group by category limit N from each category
TABLE
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
已更新
请尝试这个更新后的查询(SQL Fiddle - http://sqlfiddle.com/#!2/de35bb/9):
select videos.*
from videos
where
(
select COUNT(vid.id)
from videos AS vid
WHERE videos.category = vid.category
) <= 2
ORDER BY
videos.category, RAND()
我在这里找到了解决方案:
Using LIMIT within GROUP BY to get N results per group?
其中答案指向文章
How to select the first/least/max row per group in SQL
作者在其中描述了执行此类任务的一些技术。
上面的查询是建立在第二篇文章中提供的示例之上的,但是还有其他形式可以解决这个问题。
下面的查询从每个类别中给出不超过两个随机行:
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
TABLE
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
已更新
请尝试这个更新后的查询(SQL Fiddle - http://sqlfiddle.com/#!2/de35bb/9):
select videos.*
from videos
where
(
select COUNT(vid.id)
from videos AS vid
WHERE videos.category = vid.category
) <= 2
ORDER BY
videos.category, RAND()
我在这里找到了解决方案: Using LIMIT within GROUP BY to get N results per group? 其中答案指向文章 How to select the first/least/max row per group in SQL 作者在其中描述了执行此类任务的一些技术。 上面的查询是建立在第二篇文章中提供的示例之上的,但是还有其他形式可以解决这个问题。
下面的查询从每个类别中给出不超过两个随机行:
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