类别表:
+-----------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+--------------+------+-----+---------+----------------+
| cat_id | int(8) | NO | PRI | NULL | auto_increment |
| cat_name | varchar(255) | NO | UNI | NULL | |
| cat_description | varchar(255) | NO | | NULL | |
| cat_order | int(8) | YES | | NULL | |
+-----------------+--------------+------+-----+---------+----------------+
主题表:
+---------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+----------------+
| topic_id | int(8) | NO | PRI | NULL | auto_increment |
| topic_subject | varchar(255) | NO | | NULL | |
| topic_date | datetime | NO | | NULL | |
| topic_cat | int(8) | NO | MUL | NULL | |
| topic_by | int(8) | NO | MUL | NULL | |
+---------------+--------------+------+-----+---------+----------------+
topic_cat对应外键关系中的cat_id。
如何编写一个sql语句,返回:每个类别的最新主题加上类别名称???
到目前为止,我所拥有的是:
SELECT * FROM categories
LEFT JOIN
(SELECT topic_id, topic_subject, max(topic_date) AS MaxDate, topic_cat, topic_by
FROM topics
GROUP BY topic_subject) AS mt
ON categories.cat_id = mt.topic_cat
ORDER BY cat_order;
它从同一个类别返回多个主题,其中每个类别只需要一个主题。
最佳答案
当您试图获取greatest-n-per-group时,需要连接回原始表(topics
)以选择具有最大日期的行。因为在子查询中只提到MAX(topic_date)
不会使其他列来自找到最大日期的行。如果你还提到MIN(topic_date)
?
这应该是一个解决方案(尽管我没有测试过):
SELECT *
FROM topics AS t
JOIN (SELECT topic_cat, MAX(topic_date) AS topic_date
FROM topics
GROUP BY topic_cat) AS maxt USING (topic_cat, topic_date)
RIGHT JOIN categories AS c ON t.topic_cat = c.cat_id