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.
精彩评论