SQL连接左边得到MAX(日期)

时间:2013-04-06 12:24:01

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

我有这些表格:

  • 通知
    • id INT
    • cdate DATETIME
    • ...

  • 主题
    • ID


  • notice_theme
    • id_notice
    • id_theme

我想获得每个主题的最新通知。

SELECT id_theme, n.id
FROM notice_theme
LEFT JOIN (
    SELECT id, cdate
    FROM notice
    ORDER BY cdate DESC
) AS n ON notice_theme.id_notice = n.id
GROUP BY id_theme

结果不好。一个主意 ?感谢。

1 个答案:

答案 0 :(得分:6)

有很多方法可以解决这个问题,但我习惯这样做。需要额外的子查询来单独计算每cDate的最新ID

SELECT  a.*, c.*
FROM    theme a
        INNER JOIN notice_theme b
            ON a.ID = b.id_theme
        INNER JOIN  notice c
            ON b.id_notice = c.ID
        INNER JOIN
        (
            SELECT  a.id_theme, MAX(b.DATE_CREATE) max_date
            FROM    notice_theme a
                    INNER JOIN notice b
                        ON a.ID_Notice = b.ID
            GROUP   BY a.id_theme
        ) d ON  b.id_theme = d.id_theme AND
                c.DATE_CREATE = d.max_date