查询从表中获取前2个和第3个记录

问题描述 投票:2回答:2

我有一份学生表:

Student         SECTION
student1        A
student2        A
student3        A
student4        A
student5        B
student6        B
student7        B
student8        B

我想得到随机5名学生3 A部分学生和2 B部分学生

建议一个简单的SQL查询完成任何一次

示例:我想随机添加以下查询

select * from student where SECTION='A' LIMIT 3
select * from student where SECTION='B' LIMIT 2
mysql sql where
2个回答
2
投票

你非常接近:

(select * from student where SECTION = 'A' order by rand() LIMIT 3
) union all
(select * from student where SECTION = 'B' order by rand() LIMIT 2
)
order by rand();

子查询使用order by rand()来获得每个年级的随机学生。外面的order by rand()将五名学生随机化。

注意:这是完成所需内容的最简单方法。如果students表格中等,并且性能是一个问题,那么还有其他解决方案。


2
投票

你可以像UNION一样使用order by

(select * from student where SECTION='A' ORDER BY RAND() LIMIT 3)
UNION
(select * from student where SECTION='B' ORDER BY RAND() LIMIT 2)
© www.soinside.com 2019 - 2024. All rights reserved.