从最近的条目按字段排序多个行

时间:2018-02-07 12:17:17

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

我正在尝试返回用户列表,按用户最近一行的字段(pt_seen)排序。

这有意义吗?

到目前为止,我有:

SELECT u.users_id, 
       u.username, 
       ed.date 
FROM users u
LEFT JOIN exercises_done ed 
    ON ed.user_id = u.users_id
WHERE u.pt_id = 1
GROUP BY u.users_id

这显然只会返回分组的用户。

表格如下:

users:

users_id | pt_id | username
1        | 1     | billy
2        | 1     | bob
3        | 1     | sue


exercises_done:

exercises_done_id | user_id | pt_id | exercises_done_date | pt_seen
1                 | 1       | 1     | 2018-01-01          | 0
2                 | 1       | 1     | 2018-01-02          | 0
3                 | 1       | 1     | 2018-01-03          | 1
4                 | 2       | 1     | 2018-01-05          | 1
5                 | 3       | 1     | 2018-01-04          | 0

我正试图得到这样的结果:

users_id | username | exercises_done_date | pt_seen
1        | billy    | 2018-01-02          | 0
3        | sue      | 2018-01-04          | 0 
2        | bob      | 2018-01-05          | 1

目的是让我在列表顶部显示pt_seen值为0的用户,然后按exercise_done_date排序。

任何帮助都会很棒,

2 个答案:

答案 0 :(得分:2)

您可以在where子句中选择最近的练习,而不是使用聚合:

SELECT u.users_id, u.username, ed.*
FROM users u LEFT JOIN
     exercises_done ed
     ON ed.user_id = u.users_id
WHERE ed.exercises_done_date = (SELECT MAX(ed2.exercises_done_date)
                                FROM exercises_done ed2
                                WHERE ed2.user_id = ed.user_id
                               ) AND
      u.pt_id = 1
ORDER BY u.pt_seen, exercises_done_date DESC;

答案 1 :(得分:0)

您可以在GROUP BY之后添加ORDER BY子句。

SELECT u.users_id, u.username, ed.date FROM 
users u
LEFT JOIN exercises_done ed ON ed.user_id = u.users_id
WHERE
u.pt_id = 1
GROUP BY 
u.users_id
ORDER BY
pt_seen, exercises_done_date