我有一个包含类别和主题的网站。有些类别是彼此的父母/子女(只有一个嵌套级别)。我正在尝试从每个类别族中选择最近的主题(即,父母或孩子中最多只有一个主题)。这就是我现在正在尝试的事情:
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
如果按原样运行此查询,它将检索每个主题。如果我在末尾添加LIMIT 1
,它只检索1个(不是每个家庭1个)。如果我在最后添加LIMIT 3
,它将从所有类别中检索最近的3个。我想要每个类别的一个主题。有什么帮助吗?
答案 0 :(得分:2)
有点粗糙,但应该做你想做的事:
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
答案 1 :(得分:0)
我相信您正在寻找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