【问题标题】:How to select only one record of the left table based on its max date in MySQL?如何根据 MySQL 中的最大日期仅选择左表的一条记录?
【发布时间】:2020-03-29 02:44:35
【问题描述】:

下面是我的数据库结构

User
id       name
1        John
2        Doe
3        Smitt


Post
id       user_id      text
1        1            Hello
2        1            World
3        2            How are you?
4        3            Whatsup!
5        3            High five!


Comment
id       post_id      text                        created_at
1        1            Comment on Hello            2019-12-01
2        1            Another comment on Hello    2019-12-02
3        2            Comment on World            2019-12-03
4        1            Latest comment on Hello     2019-12-04
5        1            Some comment                2019-12-05
6        5            Five highs!                 2019-12-06
7        4            Same old, same old!         2019-12-07

如何根据 MySQL 中的MAX(created_at) 获取只有一个Comment 记录的用户列表,如下所示?

Result
id        name       comment_text          created_at
1         John       Some comment          2019-12-05
2         Doe        NULL                  NULL
3         Smitt      Same old, same old!   2019-12-07

条件:由于另一个用例,流程必须从User表转到Comment表,反之则不行!

【问题讨论】:

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


    【解决方案1】:

    您可以left join,使用相关子查询检索当前用户最新帖子的id作为加入条件:

    select
        u.id,
        u.name,
        c.text comment_text,
        c.created_at
    from user u
    left join comment c 
        on c.id = (
            select c1.id
            from post p1
            inner join comment c1 on c1.post_id = p1.id
            where p1.user_id = u.id
            order by c1.created_at desc
            limit 1
        )
    

    Demo on DB Fiddle

    编号 |姓名 |评论文本 | created_at ---: | :---- | :----------------- | :--------- 1 |约翰 |一些评论 | 2019-12-05 2 |能源部 | | 3 |施密特 |一样的老,一样的老! | 2019-12-07

    或者,如果你运行的是 MySQL 8.0,你可以使用row_number()

    select id, name, comment_text, created_at
    from (
        select
            u.id,
            u.name,
            c.text comment_text,
            c.created_at,
            row_number() over(partition by u.id order by c.created_at desc) rn
        from user u
        left join post p on p.user_id = u.id
        left join comment c on c.post_id = p.id
    ) t
    where rn = 1
    

    Demo on DB Fiddle

    【讨论】:

      猜你喜欢
      • 2018-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-16
      • 1970-01-01
      • 2022-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多