我有一個表,它包含從用戶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