我有一个表,它包含从用户a到用户b(以及更多用户)的消息,反之亦然。具有不同行值的多列组
我想从用户之间的任何对话中检索最后一条消息,另外我想按消息时间降序排列。
我的表看起来像这样:
+--------+----------+--------------+------------------+
| userid | touserid | messsagetime | message |
+--------+----------+---------------+------------------+
| 1 | 2 | 1504637613197 | hello |
| 1 | 2 | 1504637938942 | how are you? |
| 2 | 1 | 1504637970246 | i'm fine thanks. |
| 3 | 1 | 1504640245930 | hello |
| 1 | 3 | 1504640322756 | hello! |
+--------+----------+---------------+------------------+
预期输出:
+--------+----------+---------------+------------------+
| userid | touserid | messsagetime | message |
+--------+----------+---------------+------------------+
| 2 | 1 | 1504637970246 | i'm fine thanks. |
| 1 | 3 | 1504640322756 | hello! |
+--------+----------+---------------+------------------+`
不幸的是,我的MySQL知识是有限的,这是因为据我得到:
SELECT *
FROM
(SELECT *
FROM messages
WHERE userid = 1
or touserid = 1
ORDER
BY messagetime desc
) AS a
GROUP
BY userid
哪个订购它的消息时间,只有1条消息from
- to
,但不会将来自其他用户的消息分组在一起。
为样本数据创建/插入:
CREATE TABLE IF NOT EXISTS `1` ( `id` int(11) NOT NULL
AUTO_INCREMENT, `touser` int(11) NOT NULL, `fromuser` int(11) NOT
NULL, `messagetime` bigint(20) NOT NULL, `message` text COLLATE
utf8mb4_unicode_ci NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB
DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci AUTO_INCREMENT=6 ;
INSERT INTO `1` (`id`, `touser`, `fromuser`, `messagetime`, `message`)
VALUES (1, 1, 2, 1504637613197, 'hello'), (2, 1, 2, 1504637938942,
'how are you? '), (3, 2, 1, 1504637970246, 'i''m fine thanks.'), (4,
3, 1, 1504640245930, 'hello'), (5, 1, 3, 1504640322756, 'hello!');
是否有任何MySQL的魔力,将实现什么,我想在这里做什么?
提供创建和插入语句将有助于更快地为其中的某个人解决此问题 –
从user1到user2的最后一条消息应该发生什么? – RiggsFolly
@RiggsFolly它们不应该被返回,因为从user2到user1的消息已经在以后发送。 – user327685