Something in these lines will work:
SELECT id, name, category FROM ( SELECT *, IF( @prev <> category, @rownum := 1, @rownum := @rownum+1 ) AS rank, @prev := category, @rownum FROM ( SELECT * FROM products ORDER BY category, rand() ) random_prodcts ) products_ranked WHERE rank <= 2;
He arranges them randomly within categories, then pulls them out, keeping track of how many of them are received from each.
Not sure how well it will scale.
EDIT: Tried this with several thousand records, and it looks fine.
Simon
source share