I have a table which looks something like:
table: Q
---------------------------
|question| scope | type |
---------------------------
| this | A | 1 |
| that | A | 1 |
| them | A | 1 |
---------------------------
| this | A | 2 |
| that | A | 2 |
| them | A | 2 |
---------------------------
| this | B | 1 |
| that | B | 1 |
| them | B | 1 |
---------------------------
I need given a scope, I need to extract two entries from each type. If scope is A, a possible solution could be:
---------------------------
| this | A | 1 |
| them | A | 1 |
---------------------------
| that | A | 2 |
| this | A | 2 |
---------------------------
I’m currently using the following SQL statement:
SELECT tmp.question, tmp.type, tmp.scope
FROM Q
LEFT JOIN (
SELECT * FROM Q ORDER BY RAND( )
)tmp ON ( Q.type = tmp.type AND tmp.scope = 'A' )
GROUP BY tmp.type
ORDER BY Q.type
However this only returns one entry per type and for some reason a NULL row.
My question is therefore how to optimize the statement to return two rows and eliminate the NULL one?
you can change rank from 2 to whatever you want to get for each category.
http://www.sqlfiddle.com/#!2/f3946/86
try this:
Note: I used an old answer and improved for randomizing.
Old answer I got help is:
Select N records for each category and order by X