I have a table like this
ID | category | product |
---|---|---|
1 | 1 | p1 |
2 | 1 | p2 |
3 | 1 | p3 |
4 | 1 | p4 |
5 | 2 | p5 |
6 | 2 | p6 |
7 | 2 | p7 |
8 | 3 | p8 |
9 | 3 | p9 |
10 | 3 | p10 |
I am trying to select one random product for each category.
result like this :
category | product |
---|---|
1 | p3 |
2 | p7 |
3 | p8 |
i tried with this query, gives me random but not for each category without duplicates
SELECT
category, product
FROM
table
WHERE
category IN (1,2,3)
ORDER BY RAND()
LIMIT N
3
Answers
Perhaps try the following using a sub-query correlated for each category:
You can do it as follows :
Demo here
Another approach could be to make use of
PARTITION BY
: