我有以下两个表。我想选择所有具有user_type 1的用户,以及他们最近的笔记的详细信息。我想按time_created注释对结果进行排序。
users table:
user_id name user_type
1 Joe 1
2 Fred 1
3 Sam 0
4 Dave 0
notes table:
notes_id user_id note time_created
1 1 Joe 1 2019-06-05 13:45:00
2 1 Joe 2 2019-06-05 13:46:00
2 1 Joe 3 2019-06-05 13:47:00
3 2 Fred 1 2019-06-05 13:45:00
4 2 Fred 2 2019-06-05 13:46:00
5 3 Sam 1 2019-06-05 13:45:00
6 4 Dave 1 2019-06-05 13:45:00
所以查询的结果将是
user_id name note time_created
1 Joe Joe 3 2019-06-05 13:47:00
2 Fred Fred 2 2019-06-05 13:45:00
这是我到目前为止的努力
SELECT users.user_id, users.name, notes.note, notes.time_created FROM notes
INNER JOIN users ON users.id=prospect_notes.subject_id
WHERE users.user_type = 1 ORDER BY notes_time_created;
这很好,但是每个用户返回几行。我只想要包含创建的最大时间的一行。
答案 0 :(得分:1)
您可以使用相关子查询:
SELECT u.user_id, u.name, n.note, n.time_created
FROM users u JOIN
notes n
ON u.id = n.subject_id
WHERE u.user_type = 1 AND
n.notes_time_created = (SELECT MAX( n2.notes_time_created )
FROM notes n2
WHERE n2.subject_id = n.subject_id
)
ORDER BY n.notes_time_created;