我正在尝试获取特定用户的最新消息列表。我的表格如下:
+----------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+---------------------+------+-----+---------+----------------+
| id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| sender_user_id | int(11) | NO | | NULL | |
| remote_user_id | int(11) | NO | | NULL | |
| message | longtext | NO | | NULL | |
| read | tinyint(4) | NO | | NULL | |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
+----------------+---------------------+------+-----+---------+----------------+
创建表:
CREATE TABLE `messages` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`sender_user_id` int(11) NOT NULL,
`remote_user_id` int(11) NOT NULL,
`message` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
`read` tinyint(4) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
到目前为止,这是我尝试过的:
SELECT sender_user_id, remote_user_id FROM messages m1 WHERE id = (SELECT MAX(m2.id) FROM messages m2 WHERE m1.sender_user_id = m2.sender_user_id AND m1.remote_user_id = m2.remote_user_id)
这看起来很接近,但显然没有考虑到您搜索的用户 ID,它有时会返回重复项,例如:
MariaDB [snowdon]> SELECT sender_user_id, remote_user_id FROM messages m1 WHERE id = (SELECT MAX(m2.id) FROM messages m2 WHERE m1.sender_user_id = m2.sender_user_id AND m1.remote_user_id = m2.remote_user_id)
-> ;
+----------------+----------------+
| sender_user_id | remote_user_id |
+----------------+----------------+
| 1 | 2 |
| 2 | 1 |
| 3 | 1 |
+----------------+----------------+
3 rows in set (0.00 sec)
第一行和第二行是同一对话的一部分,所以我只希望最新的出现在结果中。
有人可以帮我写 SQL 吗?
萨克斯
最佳答案
我想你想要:
SELECT (CASE WHEN m.sender_user_id = ? THEN m.remote_user_id ELSE m.sender_user_id END) as other_user_id
FROM messages m
WHERE ? IN (m.sender_user_id, m.remote_user_id) AND
m.id = (SELECT MAX(m2.id)
FROM messages m2
WHERE (m2.sender_user_id, m2.remote_user_id) IN
( (m.sender_user_id, m.remote_user_id),
(m.remote_user_id, m.sender_user_id)
)
);
关于mysql - Mariadb - 从用户 ID = 变量的所有消息列表中获取最新消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58570816/