Table:
| id | productId | orderIndex | rejected |
------------------------------------------
| 1 | 1 | 0 | 1 |
| 2 | 1 | 1 | 0 |
| 3 | 1 | 2 | 0 |
| 4 | 2 | 0 | 0 |
| 5 | 2 | 1 | 1 |
| 6 | 3 | 0 | 0 |
How can I select one row for each product with a minimum ordinal index that is not rejected?
Expected Result:
| id | productId | orderIndex | rejected |
------------------------------------------
| 2 | 1 | 1 | 0 |
| 4 | 2 | 0 | 0 |
| 6 | 3 | 0 | 0 |
I tried this query but did not get the correct result:
SELECT id, productId, min (orderIndex)
FROM table
WHERE rejected = 0
GROUP BY productId
This doesn't work either:
SELECT id, productId, min (orderIndex)
FROM (
SELECT id, productId, orderIndex
FROM table
WHERE rejected = 0
) t
GROUP BY productId
mysql greatest-n-per-group
Degibons
source share