开发者

MySQL query to get list of latest updated pages, but only one result for every slug?

开发者 https://www.devze.com 2023-01-09 22:58 出处:网络
I have a table for pages with fields slug (string, not unique) and upd开发者_JAVA百科ated (datetime). I want to retrieve a list of last updated pages based on the updated field, but I only want one re

I have a table for pages with fields slug (string, not unique) and upd开发者_JAVA百科ated (datetime). I want to retrieve a list of last updated pages based on the updated field, but I only want one result for every slug (since slugs can be re-used across pages in this case). What to do?

I tried this:

SELECT * FROM `pages`
GROUP BY `slug`
ORDER BY `updated` DESC

That gives only one result per slug, but not always the last updated one.


This is MSSQL - but will return 'ties' if a page is updated 2 or more times at exactly the same datetime.

SELECT * FROM pages
WHERE Updated In
(
SELECT Max(Updated)
FROM pages
GROUP BY slug
)


This should work for you:

SELECT *
FROM pages p1
LEFT JOIN pages p2 ON p1.slug = p2.slug AND p1.updated < p2.updated
WHERE p2.updated IS NULL
ORDER BY p1.updated DESC

See http://dev.mysql.com/doc/refman/5.1/en/example-maximum-column-group-row.html.

0

精彩评论

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

关注公众号