I have a table "products" with a column called "store_id".
This table has a lot af products from many stores.
I need to select 4 random products from 4 specific stores (id: 1, 34, 45, 100).
How can I do that?
I’ve tried to like this:
SELECT * FROM products WHERE store_id IN (1, 34, 45, 100)
But that query returns duplicated records (by store_id).
I need the following result:
store_id | title |
---|---|
1 | title a |
34 | title b |
45 | title c |
100 | title d |
2
Answers
Use the DISTINCT construct to get unique records for the desired column:
Demo in sqldaddy.io
To get a true random pick of the products use a
row_number
function with random order.This query shows all data with a random index of the product for each store
To get only one product per store simple filter with
rn=1
Note this query will produce a different result on each run. If you need a stability you must call setseed before each execution. E.g.