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 ramdom 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 |
>Solution :
Use the DISTINCT construct to get unique records for the desired column:
SELECT distinct on (store_id) store_id, title FROM products WHERE store_id IN (1, 34, 45, 100);
Demo in sqldaddy.io