MYSQl 根据类型排序各取3个,随机取,sql怎么写?
发布网友
发布时间:2022-04-08 19:19
我来回答
共3个回答
热心网友
时间:2022-04-08 20:48
下面这个不知是否可行:
create table books(`id` int, `name` varchar(16),`type` varchar(16));
insert into books(`id`,`name`,type)
select 1 as `id`, 'book11' as `name`, 'type1' as `type`
union all
select 2, 'book12', 'type1'
union all
select 3, 'book13', 'type1'
union all
select 4, 'book14', 'type1'
union all
select 5, 'book15', 'type1'
union all
select 6, 'book21', 'type2'
union all
select 7, 'book22', 'type2'
union all
select 8, 'book23', 'type2'
union all
select 9, 'book24', 'type2'
union all
select 10, 'book25', 'type2'
union all
select 11, 'book26', 'type2'
union all
select 12, 'book31', 'type3'
union all
select 13, 'book32', 'type3'
union all
select 14, 'book33', 'type3'
select t.`id`, t.`name`, t.type, t.rank
from (
select b.`id`, b.name, b.type,
if(@type = b.type, @rank := @rank + 1, @rank := 1) as rank,@type:=b.type
from (select id, name, type from books order by type asc, rand() desc) as b,
(select @type := null, @rank := 0) as a
) as t
where t.rank<=3;
追问你这种似乎是可以 但是我类型不止3个 rank 该怎么改? 似乎改了不对了。
追答数据是用于测试的,我只维护了3种类型,3种以上也是可以的。
这个rank是对相同类型的随机排序,rank<=3表示取每种类型的前3个(随机排序过的)。
热心网友
时间:2022-04-08 22:06
没啥很好的想法,但union all肯定行,来2次就行了
select * from (
SELECT * FROM (SELECT * FROM 表 ORDER BY RAND()) AS a
GROUP BY a.类型)t1
union all
select * from (
SELECT * FROM (SELECT * FROM 表 ORDER BY RAND()) AS a
GROUP BY a.类型)t2
union all
select * from (
SELECT * FROM (SELECT * FROM 表 ORDER BY RAND()) AS a
GROUP BY a.类型)t3追问谢谢,但是感觉楼上更好。
热心网友
时间:2022-04-08 23:41
大侠,你什么意思,没有明白,可否说明白点。