订单表按最近一次在另一个表中的匹配

时间:2017-02-02 20:17:59

标签: mysql sorting

我想根据最近的照片上传对用户表进行排序。 我不会使用上传日期信息 - 只需要进行分类。

Users
    +----+--------+
    | id |  name  |
    +----+--------+
    |  1 | John   |
    |  2 | Alice  |
    |  3 | Robert |
    |  4 | Fred   |
    +----+--------+

    Photos
    +----+---------+------+------------+
    | id |  photo  | user |  uploaded  |
    +----+---------+------+------------+
    |  1 | aaa.jpg |    1 | 2012.01.01 |
    |  2 | aba.jpg |    1 | 2013.01.01 |
    |  3 | bbb.jpg |    4 | 2014.01.01 |
    |  4 | ccc.jpg |    4 | 2015.01.01 |
    |  5 | ddd.jpg |    4 | 2016.01.01 |
    +----+---------+------+------------+

    Expected resut
        +----+--------+------------------+
        | id |  name  |    lastUpload    |
        +----+--------+------------------+
        |  4 | Fred   | 2016.01.01       |
        |  1 | John   | 2013.01.01       |
        |  2 | Alice  | null or whatever |
        |  3 | Robert | null or whatever |
        +----+--------+------------------+

1 个答案:

答案 0 :(得分:0)

您可以使用左连接和聚合最大功能与分组

    select a.id, a.name, max(b.uploaded) as lastupload
    from users as a
    left  join Photos as b on a.id = b.user
    group by a.id
    order by lastupload, a.name