我如何编写这个涉及连接的简单sql语句?

时间:2014-05-28 22:49:17

标签: mysql sql join inner-join greatest-n-per-group

分类表:

+-----------------+--------------+------+-----+---------+----------------+
| 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;

它返回同一类别中的多个主题,其中我只需要每个类别一个主题。

2 个答案:

答案 0 :(得分:3)

当您尝试获取时,需要重新加入原始表(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

答案 1 :(得分:-1)

第一个,简单但不那么强大的解决方案是在主题选择GROUP BY topic_cat和ORDER BY topic_date:

SELECT * FROM categories 
LEFT JOIN
   (SELECT topic_id, topic_subject, topic_date, topic_cat, topic_by 
      FROM topics 
     ORDER BY topic_date DESC
     GROUP BY topic_cat) AS mt 
ON categories.cat_id = mt.topic_cat 
ORDER BY cat_order;

我认为MySQL应该能够处理这个问题,即使它不是其他数据库引擎的普遍解决方案,其中分组规则更严格。