简体   繁体   English

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

[英]SQL join left get MAX(date)

i have these tables : 我有这些表:

  • notice 注意
    • id INT id INT
    • cdate DATETIME cdate DATETIME
    • ... ...

  • theme 主题
    • id ID
    • name 名称

  • notice_theme notice_theme
    • id_notice id_notice
    • id_theme id_theme

I want to get the latest notices for each 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

The result is not good. 结果并不好。 An idea ? 一个主意 ? Thanks. 谢谢。

There are so many ways to solve this but I'm used to do it this way. 有很多方法可以解决这个问题,但我习惯这样做。 An extra subquery is needed to separately calculate the latest cDate for every ID . 需要额外的子查询来分别计算每个ID的最新cDate

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM