I have a database (dates are just examples for order sake)...
--------------------- | user | item | date | --------------------- | 1 | a | 123 | | 3 | b | 124 | | 1 | c | 125 | | 2 | d | 126 | | 5 | i | 127 | | 4 | e | 128 | | 6 | f | 129 | | 9 | g | 130 | | 3 | h | 131 | | 9 | s | 132 | | 1 | j | 133 | | 2 | k | 134 | | 1 | l | 135 | | 1 | m | 136 | | 1 | n | 137 | | 8 | o | 138 | | 5 | p | 139 | | 9 | q | 140 | | 7 | r | 141 | ---------------------
I would like to get all records up to the first 8 unique users, which would make the results...
--------------------- | user | item | date | --------------------- | 1 | a | 123 | | 3 | b | 124 | | 1 | c | 125 | | 2 | d | 126 | | 5 | i | 127 | | 4 | e | 128 | | 6 | f | 129 | | 9 | g | 130 | | 3 | h | 131 | | 9 | s | 132 | | 1 | j | 133 | | 2 | k | 134 | | 1 | l | 135 | | 1 | m | 136 | | 1 | n | 137 | | 8 | o | 138 | ---------------------
Then from those records, I'd like to get the most recent 4 records per unique user, making the results look like...
--------------------- | user | item | date | --------------------- | 3 | b | 124 | | 2 | d | 126 | | 5 | i | 127 | | 4 | e | 128 | | 6 | f | 129 | | 9 | g | 130 | | 3 | h | 131 | | 9 | s | 132 | | 1 | j | 133 | | 2 | k | 134 | | 1 | l | 135 | | 1 | m | 136 | | 1 | n | 137 | | 8 | o | 138 | ---------------------
Ideally I would be able to do this with one query. The closest I've been able to come is with this query:
SELECT users, GROUP_CONCAT(items) FROM db GROUP BY users ORDER BY date LIMIT 8
But GROUP_CONCAT gives back all results for that user, not just the amount in the selection.
I've also tried...
SELECT users FROM db AS u1 JOIN (SELECT DISTINCT users FROM db) AS u2 ON u1.users = u2.users
from another suggestion I found but this also didn't work.
I've tried a ton of other things that I didn't really save because they didn't work and I was pretty confident I'd figure it out, but it's been two weeks and I haven't got close. If any SQL gurus are out there that can point me in the right direction, that would be really great. Thanks.