Skip to content Skip to sidebar Skip to footer

Query To Get Top 2 And 3 Rd Records From A Table

I have a table list of Student: Student SECTION student1 A student2 A student3 A student4 A student5 B student6 B student7

Solution 1:

You are pretty close:

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

The subqueries use order by rand() to get random students with each grade. The outer order by rand() randomizes the five 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.

Solution 2:

You can use UNION along order by like

(select*from student where SECTION='A'ORDERBY RAND() LIMIT 3)
UNION
(select*from student where SECTION='B'ORDERBY RAND() LIMIT 2)

Post a Comment for "Query To Get Top 2 And 3 Rd Records From A Table"