简体   繁体   中英

How to select latest row by a user_id

I have the following table:

content: id, user_id, markdown

How do I select the latest id created by a certain user?

SELECT * FROM content
WHERE user_id = 2

So if rows 12,13 and 14 have user_id as 2, I want to select row 14

SELECT * FROM content
WHERE user_id = 2
ORDER BY id DESC
LIMIT 1

Also, if you have a table of users and you want to get the latest record for each:

SELECT c.*
FROM content c
    INNER JOIN (SELECT user_id, max(id) as maxid 
                FROM content 
                GROUP BY user_id) as c1 on c.id = c1.maxid

In MySQL I think you'd need:

SELECT *
FROM content
WHERE user_id = 2
ORDER BY id DESC
LIMIT 1

You could do a subselect and select the MAX timestamp (which may be safer) - but it doesn't look like you have a timestamp.

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