代码之家  ›  专栏  ›  技术社区  ›  brinch

在mysql中,如何连接第二个表并获取具有最新日期的行?

  •  2
  • brinch  · 技术社区  · 8 年前

    Question Commentary . 这就是他们的样子:

    问题 :Id,标题

    实况报道 :问题ID,内容,已创建(日期字段)

    0对多关系 在问题和评论之间。也就是说,一个问题可以有0。。n注释。

    我相信我在这个查询中几乎成功了,除了它只检索到 无评论

    select 
        q.Id AS Id,
        q.Title AS Title,
        c.Content AS Content
    from question AS q
    left join commentary as c on c.QuestionId = q.Id
    where
       c.Created = (
          select MAX(created)
          from commentary
          where questionid = q.Id
        )
    

    如何调整脚本?

    1 回复  |  直到 8 年前
        1
  •  1
  •   LAS    8 年前

    where子句仅返回注释行具有最大创建日期的行,当没有注释记录时,该日期不是真的。您只需要包括注释question\u ID为null的行,当没有注释时,该行应始终为true。

    select 
        q.Id AS Id,
        q.Title AS Title,
        c.Content AS Content
    from question AS q
         left join commentary as c on c.QuestionId = q.Id
    where
       c.Created = (
          select MAX(created)
          from commentary
          where questionid = q.Id
       )
       or
       c.QuestionId is null