感谢您阅读此疑问。无论该对话是一对一还是群组对话,我都很难从每个对话中获取最新消息。
我已经弄清楚了如何获取一对一聊天的最新消息。但很难为该组获取最新消息。
CREATE TABLE messages ( sender_id TEXT, receiver_id TEXT, group_id TEXT, message TEXT, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP );
要测试查询的行
INSERT INTO messages (sender_id, receiver_id, group_id, message, timestamp) VALUES
('user1', NULL, 'groupA', 'Hello, how are you?', '2023-11-04 12:00:00'),
('user2', NULL, 'groupA', 'I am fine, thank you.', '2023-11-04 12:05:00'),
('user3', 'user4', NULL, 'What is the weather like today?', '2023-11-04 12:10:00'),
('user4', 'user3', NULL, 'It is sunny and warm.', '2023-11-04 12:15:00'),
('user1', NULL, 'groupA', 'Can we meet tomorrow?', '2023-11-05 10:00:00'),
('user2', NULL, 'groupA', 'Sure, what time?', '2023-11-05 10:05:00'),
('user3', 'user4', NULL, 'Did you finish the report?', '2023-11-05 11:00:00'),
('user4', 'user3', NULL, 'Almost, I''ll send it by evening.', '2023-11-05 11:05:00'),
('user5', NULL, 'groupC', 'Let''s go for dinner tonight.', '2023-11-05 18:00:00'),
('user6',NULL, 'groupC', 'Sounds good, where should we go?', '2023-11-05 18:05:00'),
('user7', 'user8', NULL, 'I need help with this code.', '2023-11-06 09:00:00'),
('user8', 'user7', NULL, 'Sure, send it over.', '2023-11-06 09:05:00'),
('user1', NULL, 'groupD', 'Can you join the meeting tomorrow?', '2023-11-06 14:00:00'),
('user3', NULL, 'groupD', 'Yes, I can make it.', '2023-11-06 14:05:00');
查询获取一对一聊天的最新消息
SELECT m1.*
FROM messages m1
INNER JOIN
(
SELECT t.v1 AS sender_id, t.v2 AS receiver_id, MAX(t.timestamp) AS maxTime
FROM
(
SELECT CASE WHEN sender_id < receiver_id THEN sender_id ELSE receiver_id END AS v1,
CASE WHEN sender_id < receiver_id THEN receiver_id ELSE sender_id END AS v2,
timestamp
FROM messages
) t
GROUP BY t.v1, t.v2
) m2
ON ((m1.sender_id = m2.sender_id AND m1.receiver_id = m2.receiver_id) OR (m1.sender_id = m2.receiver_id AND m1.receiver_id = m2.sender_id)) AND m1.timestamp = m2.maxTime
我尝试过使用group_id进行分组。但只能获取 group_id 为 NULL 的行。
输出应仅包含每次对话的最新内容。
('user2', NULL, 'groupA', 'Sure, what time?', '2023-11-05 10:05:00'),
('user4', 'user3', NULL, 'Almost, I''ll send it by evening.', '2023-11-05 11:05:00'),
('user6',NULL, 'groupC', 'Sounds good, where should we go?', '2023-11-05 18:05:00'),
('user8', 'user7', NULL, 'Sure, send it over.', '2023-11-06 09:05:00'),
('user3', NULL, 'groupD', 'Yes, I can make it.', '2023-11-06 14:05:00')
只需选择每组中时间戳最大的行即可。
SELECT *
FROM messages
WHERE group_id IS NOT NULL
GROUP BY group_id
HAVING timestamp = MAX(timestamp)