2

I have 10000 categories of posts and 1200000 posts (each post has publication dae). I want to get date of most recent post for each category using one or two SQL queries. This is structure of database:

Categories
+--+----+
|id|name|
+--+----+

CategoriesToPosts
+--------+----+
|category|post|
+--------+----+

Posts
+--+------------+-   -+
|id|lastModified| ... |
+--+------------+-   -+
4

1 回答 1

2

Use a JOIN, GROUP BY and MAX:

SELECT
    CategoriesToPosts.category,
    MAX(Posts.lastModified) AS lastModified
FROM CategoriesToPosts
LEFT JOIN Posts
ON Posts.id = CategoriesToPosts.post
GROUP BY CategoriesToPosts.category
于 2012-04-08T18:39:03.423 回答