简体   繁体   中英

Query get all latest records based on user_id

I have a table called photos that has hundred of thousands of user uploaded photos.

Each user can obviously upload several photos.

The table schema is:

id, 
user_id, 
photo, 
date_created

I just want to get the latest record that each user_id has posted..

I tried:

SELECT * FROM photos 
GROUP BY user_id 
ORDER BY date_created desc LIMIT 300

But that is obviously bringing back a lot of strange results.

This seems like an easy query, but I have done hours and hours of research on stack overflow and reading so many different articles on Google, and I can't for the life of me figure this simple query out.

This should get you the latest row for every user:

SELECT p.user_id, photo, date_created FROM photos p
JOIN (
    SELECT user_id, MAX(date_created) max_date FROM photos GROUP BY user_id
) max_dates ON p.user_id = max_dates.user_id AND p.date_created = max_dates.max_date

Sample SQL Fiddle

select p1.user_id, p1.photo, p1.date_created 
  from photos p1  left join photos p2 
    on p1.id < p2.id and p1.user_id = p2.user_id 
  where p2.id is null

try that

EDIT forgot table name, my bad. added it in. also, here's a fiddle to see: http://sqlfiddle.com/#!9/a72f6/3

Check this out. I used HAVING MAX(date_created) to retrieve the records which are currently created/uploaded.

SELECT user_id 
FROM photos 
GROUP BY user_id
HAVING MAX(date_created) 
ORDER BY date_created DESC LIMIT 300

I believe what you want is to get rid of that GROUP BY and use a regular 'WHERE user_id = 'something', being the rest correct.

I tried a query like yours and the result was only one record by each 'user_id', lets say. GROUP BY usually uses a WHERE in the sentence...

http://www.w3schools.com/sql/sql_groupby.asp

I hope that helps :) If you get an error, please post it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM