MySQL random query but with distinct values from 1 column
I've a query like
SELECT Id, Category, Title FROM articles WHERE 1 ORDER BY RAND() LI开发者_Python百科MIT 0,20
I've 20 categories and I want 1 random article per category. How? With this query I always have some category not selected.
Thanks
try getting DISTINCT Category
from the table, like
SELECT Id, DISTINCT Category, Title FROM articles WHERE 1 ORDER BY RAND() LIMIT 0,20
Try grouping by category. Haven't tested this, but something like:
SELECT Id, Category, Title FROM articles GROUP BY Category ORDER BY RAND() LIMIT 0,20
精彩评论