Theres a note
表,每个用户都可以有多个备注。我有一个用户表,其中有一个名为last_note
的列null
,需要根据notes
表中每个用户的最后一个注释进行填充。
为我所做的每个用户选择最新的备注:
SELECT * FROM users
GROUP BY user_id
ORDER BY tm DESC
但是,由于显而易见的原因,我无法将group by和order by子句合并到我的更新查询中:
UPDATE users u
JOIN note n
ON u.id = n.user_id
SET u.last_note = n.note
GROUP BY n.user_id
ORDER BY n.tm DESC
我想知道是否有人可以帮助我弄清楚如何实现这一目标。
提前致谢!
答案 0 :(得分:1)
试试这个:
UPDATE users u
INNER JOIN (SELECT n.user_id, n.note
FROM note n
INNER JOIN (SELECT n.user_id, MAX(n.noteId) noteId
FROM note n GROUP BY n.user_id
) AS A ON n.user_id = A.user_id AND n.noteId = A.noteId
) n ON u.id = n.user_id
SET u.last_note = n.note
或强>
UPDATE users u
INNER JOIN (SELECT n.user_id, n.note
FROM (SELECT n.user_id, n.note
FROM note n ORDER BY n.user_id, n.noteId DESC
) n
GROUP BY n.user_id
) n ON u.id = n.user_id
SET u.last_note = n.note