[英]ORDER BY date SQL with LEFT JOIN for messaging
I have a problem that seems to be simple to solve but is not.我有一个问题似乎很容易解决,但实际上并非如此。
I have a MySQl database that storeS user, and chat sessions and chat lines of users.我有一个 MySQl 数据库来存储用户,以及用户的聊天会话和聊天线路。
Here's a part of UML schema of my database:这是我的数据库的 UML 模式的一部分:
In chat_sessions we store only all session id (Auto increment)在 chat_sessions 我们只存储所有 session id(自动递增)
In chat_sessions_members we store all of the user session在 chat_sessions_members 我们存储所有用户 session
In chat_lines we store all line of the chat_sessions在 chat_lines 我们存储所有的聊天会话行
Example:例子:
The problem is how to get session of specific user and at the same time get the last lines if exist.问题是如何获取特定用户的 session 并同时获取最后一行(如果存在)。
My last try gives me this code:我的最后一次尝试给了我这个代码:
SELECT `chat_sessions_members`.`session_id`, ANY_VALUE(`send_at`) AS `send_at`, ANY_VALUE(`line`) AS `line`
FROM `chat_sessions_members`
LEFT JOIN `chat_lines` ON `chat_sessions_members`.`session_id` = `chat_lines`.`session_id`
WHERE `user_id` = '1'
GROUP BY `session_id`
ORDER BY DATE(`send_at`) DESC
But it's not an ordered reply.但这不是一个有序的答复。
I know a lot of post talk about that but I don't understand all of them.我知道很多帖子谈论这个,但我不明白所有这些。
If I understand correctly, you want the last (most recent) line for each session that has a given user.如果我理解正确,您需要具有给定用户的每个 session 的最后(最新)行。 If so, you can use
ROW_NUMBER()
to identify the last line and LEFT JOIN
to identify the user:如果是这样,您可以使用
ROW_NUMBER()
来识别最后一行并使用LEFT JOIN
来识别用户:
SELECT cl.*
FROM chat_sessions_members csm LEFT JOIN
(SELECT cl.*,
ROW_NUMBER() OVER (PARTITION BY cl.session_id ORDER BY cl.send_at DESC) as seqnum
FROM chat_lines cl
) cl
ON cl.session_id = csm.session_id AND seqnum = 1
WHERE csm.user_id = 1
ORDER BY DATE(cl.send_at) DESC;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.