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:
SELECT x.question,
x.scope,
x.type
FROM (
SELECT bp.question, bp.scope, bp.type,
CASE WHEN bp.type = @type
THEN @rownum := @rownum + 1
ELSE @rownum := 1
END AS rank,
@type := bp.type
FROM (select * from Q order by rand()) bp
JOIN (SELECT @rownum := 0, @type := NULL) r
WHERE bp.scope = 'A'
ORDER BY type
) x
WHERE x.rank <= 2
order by x.type
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With