Reputation: 67
In below SQL query I need 25 rows containing product = 'y' and 25 rows having product = 'n'. Product is a column having Y/N value only. In limit of random 50 rows I need 25 rows from each values.
SELECT qno
FROM `wp_question_bank`
where brand='XYZ'
and department='DOMESTIC'
and product = 'y'
and priority = 'p1'
ORDER BY RAND() limit 50
Kindly assist. I have tried Union but it didn't work.
Upvotes: 0
Views: 54
Reputation: 1269703
If you have enough rows of each type, you can do this without a subquery:
SELECT qno
FROM `wp_question_bank`
WHERE brand = 'XYZ' AND department = 'DOMESTIC' AND
product IN ('n', 'y') AND priority = 'p1'
ORDER BY ROW_NUMBER() OVER (PARTITION BY product ORDER BY rand())
LIMIT 50;
Upvotes: 0
Reputation: 5316
Simply use UNION
for each product type:
(SELECT qno
FROM `wp_question_bank`
WHERE brand='XYZ' AND department='DOMESTIC' AND product = 'y' AND priority = 'p1'
ORDER BY RAND()
LIMIT 25)
UNION ALL
(SELECT qno
FROM `wp_question_bank`
WHERE brand='XYZ' AND department='DOMESTIC' AND product = 'n' AND priority = 'p1'
ORDER BY RAND()
LIMIT 25)
Upvotes: 1
Reputation: 222442
You could use row_number()
if you are running MySQL 8.0:
select qno
from (
select qno, row_number() over(partition by product order by rand()) rn
from wp_question_bank
where brand='XYZ' and department='DOMESTIC' and priority = 'p1'
) t
where rn <= 25
Upvotes: 0