You can use ROW_NUMBER()
window function with ORDER BY RAND()
to assign a random ordering for the rows of each type
.
Then select the number of rows you want for each type
.
This will work in MySql:
SELECT *
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY type ORDER BY RAND()) rn
FROM fruits
WHERE type IN (1, 3, 4)
) t
WHERE rn <= CASE type
WHEN 1 THEN 2 -- 2 rows for type = 1
WHEN 3 THEN 1 -- 1 row for type = 3
WHEN 4 THEN 2 -- 2 rows for type = 4
END
See a simplified demo.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…