Developer Developer - 4 years ago 79
MySQL Question

Get a Students with 2 Different Limit Conditions

I have a table list of Student:

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


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

Case : if there are 2 A SECTION Records then I will get only 4 Records as Results Right, Can I Maintain Overall 5 Records which include both SECTION A & B if there are not enough students. Can you Suggest me a Solution

Done any once a Suggest a Simple SQL Query

Answer Source
SELECT student, section 
  FROM 
     ( SELECT 1 seq, student, section FROM my_table WHERE section = 'a' ORDER BY RAND() LIMIT 3) x
 UNION
     ( SELECT 2 seq, student, section FROM my_table WHERE section = 'b' )
 ORDER 
    BY seq, RAND() LIMIT 5;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download