I have two tables:
table_1
uid | xid | name
table_2
uid | elements | time | pkey
I want to select multiple rows of xid, elements and time where time is the 10 smallest values and uid (or xid) is distinct.
uid, xid in in table_1 is unique and the relationship between uid in table_1 and table_2 is one to many..
I tried something like this but its not really working too well:
SELECT table_1.xid, MIN(table_2.time), table_2.elements
FROM table_1, table_2
WHERE table_1.uid= table_2.uid
GROUP BY table_2.uid
LIMIT 10
Lets take some data to play around with:
table_1
uid | xid | name
1 | 435 | John
2 | 596 | Jane
table_2
uid | elements | time | pkey
1 | 1 | 567 | 0
2 | 2 | 335 | 1
1 | 1 | 435 | 2
1 | 2 | 456 | 3
2 | 1 | 337 | 4
1 | 1 | 428 | 5
How would I select the top 2 distinct results for each UID? In this case:
fid| elements | time
596| 2 | 335
435| 1 | 428
Thanks!!!
In case people don't understand why lexu's solution does not work - it does not bind to primary key on table 2
If I change above data to :
table_2
uid | elements | time | pkey
1 | 1 | 567 | 0
2 | 2 | 335 | 1
1 | 1 | 435 | 2
1 | 2 | 456 | 3
2 | 1 | 337 | 4
1 | 2 | 428 | 5
Keep table_1 the same then the result should be:
fid| elements | time
596| 2 | 335
435| 2 | 428
but with @lexu's solution result is:
fid| elements | time
596| 2 | 335
435| 1 | 428
Nonetheless, thanks everyone for the help and especially @eagle!