查询以从表中获取前 2 和 3 条记录 [英] Query to get top 2 and 3 rd Records from a Table

查看:59
本文介绍了查询以从表中获取前 2 和 3 条记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个学生表:

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

我想要总共随机 5 个学生3 A科学生和2 B组学生

I want to get total Randomly 5 Students 3 A Section Students and 2 B Section Students

建议一个简单的 SQL 查询,只做一次

Done any once a Suggest a Simple SQL Query

示例:我想随机搜索以下查询

Example : I want to club the below queries Randomly

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() 随机分配五个学生.

The subqueries use order by rand() to get random students with each grade. The outer order by rand() randomizes the five students.

注意:这是实现您想要的最简单的方法.如果 students 表甚至是中等大并且性能是一个问题,那么还有其他解决方案.

Note: This is the simplest way to accomplish what you want. If the students table is even moderately large and performance is an issue, there are alternative solutions.

这篇关于查询以从表中获取前 2 和 3 条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆