Subquerying with a limit
I have a site with categories and topics. Some categories are parents/children of each other (only one nested level). I'm trying to select the most recent topic from each family of categories (i.e. at most one topic from either a parent or child). Here's what I'm trying now:
SELECT topics.id
FROM topics, categories
WHERE topics.category_id = categories.id
AND ( categories.id IN ( 1, 2, 3 )
OR categories.parent IN ( 1, 2, 3 ))
ORDER BY topics.posted DESC
If I run this query as it is, it retrieves every single topic. If I add LIMIT 1
at the end, it only re开发者_高级运维trieves 1 total (not 1 per family). If I add LIMIT 3
at the end, it'll retrieve the 3 most recent from all categories. I want one topic from each category. Any help?
A bit rough, but should do what you want:
SELECT topics.id FROM
(SELECT MAX(topics.posted) AS date, categories.id AS id
FROM topics, categories
WHERE topics.category_id = categories.id
AND ( categories.id IN ( 1, 2, 3 )
OR categories.parent IN ( 1, 2, 3 ))
GROUP BY categories.id) t1
JOIN topics
ON topics.posted = t1.date AND topics.category_id = ti.id
I believe you are looking for GROUP BY:
SELECT topics.id,MAX(topics.posted) AS postDate
FROM topics, categories
WHERE topics.category_id = categories.id
AND ( categories.id IN ( 1, 2, 3 )
OR categories.parent IN ( 1, 2, 3 ))
GROUP BY topics.category_id
ORDER BY topics.posted DESC
精彩评论