查询从 Table 中获取前 2 和第 3 条记录

Query to get top 2 and 3 rd Records from a Table

我有一个 table 学生名单:

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

你很接近:

(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 table 相当大并且性能是个问题,还有其他解决方案。

您可以像

一样在 order by 中使用 UNION
(select * from student where SECTION='A' ORDER BY RAND() LIMIT 3)
UNION
(select * from student where SECTION='B' ORDER BY RAND() LIMIT 2)