我正在尝试获取一行中的对话列表以及与其关联的参与者以及给定用户的最后一条消息。我正在寻找的结果是这样的:
**| conversationId | participants | text | timestamp |**
67 aester,bester Hello 00:00:00
上面的模型只是一行。我正在尝试获取具有上述结果的所有行。文本列是与该对话关联的最后一条消息。
这是我的模型:
用户
userId|username|
87 aester
89 cester
96 bester
对话
|conversationId|
67
68
消息
| messageId | text | timestamp | conversation_id | user_id
41 Hello 00:00:00 67 87
42 Hey 00:00:00 68 89
用户对话
| id | conversation_id | user_id
3 67 87
4 67 96
5 68 89
如何查询上述模型以获得所需的结果?
当前更新:
SELECT conversations.`conversationId` as conversationId,
GROUP_CONCAT(users.`username`) as participants FROM users
LEFT JOIN user_conversations
ON users.`userId` = user_conversations.`user_id`
LEFT JOIN conversations
ON user_conversations.`conversation_id` =
conversations.`conversationId`
WHERE EXISTS (SELECT * FROM user_conversations WHERE
user_conversations.user_id = 87)
GROUP BY conversations.`conversationId`;
上面的内容是我想要的,除了我无法弄清楚如何获取每行中的最后一条消息:
| conversationId | participants |
67 aester,bester
68 cester
最佳答案
如果您想要对话列表,那么首先我们从 UserConversations
开始,获取每个 conversation_id
的参与者列表
SELECT uc.`conversation_id`,
GROUP_CONCAT(u.`username`) as participants
FROM UserConversations1 uc
JOIN Users1 u
ON uc.`user_id`= u.`userId`
GROUP BY `conversation_id`
HAVING COUNT(IF(uc.`user_id` = 87, 1, NULL)) > 0;
-- This check if the user in on the conversation.
然后我们找到每个conversation_id
的最后一条消息是什么
SELECT `conversation_id` , MAX(`messageId`) as `messageId`
FROM Messages1
GROUP BY `conversation_id`;
然后我们将所有内容结合在一起:
SELECT conversation.`conversation_id`,
conversation.`participants`,
m.text,
m.timestamp
FROM ( SELECT uc.`conversation_id`,
GROUP_CONCAT(u.`username`) as `participants`
FROM UserConversations1 uc
JOIN Users1 u
ON uc.`user_id`= u.`userId`
GROUP BY `conversation_id`
HAVING COUNT(IF(uc.`user_id` = 87, 1, NULL)) > 0) as conversation
JOIN ( SELECT `conversation_id` , MAX(`messageId`) as `messageId`
FROM Messages1
GROUP BY `conversation_id`) as last_message
ON conversation.`conversation_id` = last_message.`conversation_id`
JOIN Messages1 m
ON m.`messageId` = last_message.`messageId`;
输出
注意:我必须在表名称中添加 1
,因为有些表已经在我进行演示的平台上,并且无法删除它。
关于mysql - SQL查询一行中同一列的多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46224992/