user
id | name | age |
---|---|---|
1 | anna | 6 |
2 | john | 10 |
3 | lord | 50 |
cats
id | name | userID |
---|---|---|
1 | miez | 1 |
2 | caty | 1 |
3 | random | 2 |
4 | idk | 3 |
When using
SELECT U.id, C.name FROM user U
INNER JOIN cats C ON U.id = C.id
LIMIT 2
I get as a
result
UserID | CatName |
---|---|
1 | miez |
1 | caty |
What I want is to limit my rows by the distinct values of UserID, like this
SELECT U.id, C.name FROM user U
INNER JOIN cats C ON U.id = C.id
LIMIT 2 <distinct U.id rows>
UserID | CatName |
---|---|
1 | miez |
1 | caty |
2 | random |
People suggested using limit in subqueries and check if UserID is in the return like
... WHERE UserID IN (SELECT id FROM User LIMIT 2)
but this only works well for small tables and is not an elegant solution for good performance. My idea was using DENSE_RANK(), like:
SELECT U.id, C.name FROM user U
DENSE_RANK() OVER (ORDER BY U.id) as rows,
INNER JOIN cats C ON U.id = C.id
WHERE rows < 50
but it is not working either.