我有一个学生表格列表:
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
答案 0 :(得分: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
表格中等,并且性能是一个问题,那么还有其他解决方案。
答案 1 :(得分: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)