开发者

How to select latest row by a user_id

I have the following table:

content开发者_Go百科: 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜