0

For the query below, it currently selects from the table 50 records at random which have either job A or B. What I'm interested in is whether this can be modified to obtain 50 records at random while ensuring that an equal amount of people with job A and an equal amount of job B are selected i.e. 25 for each.

Is this possible within a single query?

"SELECT x, y, FROM table WHERE (job = 'A' OR job = 'B') ORDER BY RAND() LIMIT 50"

Any help/direction is greatly appreciated. I'm unsure where to begin searching as if you even attempt to look with keywords of 'where' and 'equal' you're directed to greater than or equal examples etc.

nat1707828
  • 877
  • 2
  • 11
  • 18
  • Does each group have at least 25 records? – Gordon Linoff Nov 19 '14 at 00:40
  • at this stage yes. The limit itself will be varied though, and from what I can tell if it falls short of having enough for each group it will just stop when there are no more records left for that group i.e. if group B only had 10 in the above example it would split 25-10. This is fine for its purpose. – nat1707828 Nov 19 '14 at 04:47

1 Answers1

3

One option is to use union

 (SELECT x, y, FROM table WHERE job = 'A' 
 ORDER BY RAND() LIMIT 25)
 UNION
 (SELECT x, y, FROM table WHERE job = 'B' 
 ORDER BY RAND() LIMIT 25)
radar
  • 13,270
  • 2
  • 25
  • 33