2012-07-05 45 views
1

我想實現一個使用mysql進行存儲的消息系統。mysql select ids pair的最後一項

這是表:

CREATE TABLE `message` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 
    `id_from` int(10) unsigned NOT NULL, 
    `id_to` int(10) unsigned NOT NULL, 
    `time` datetime NOT NULL, 
    `message` varchar(200) COLLATE utf8_unicode_ci NOT NULL, 
    PRIMARY KEY (`id`) 
); 

id_from是MSG發件人,id_to是MSG接收機。

下面插入4個消息,用於測試目的:

INSERT INTO `message`(`id`,`id_from`,`id_to`,`time`,`message`) VALUES 
(1,1,2,'2012-07-05 12:18:49','msg1'), 
(2,2,1,'2012-07-05 12:18:58','msg2'), 
(3,3,1,'2012-07-05 12:19:04','msg3'), 
(4,1,3,'2012-07-05 12:19:10','msg4'); 

我想做的事,而不是成功,是建立一個查詢,獲取最後的發送或接收消息,每對(id_from,id_to)一特定用戶。 在這種情況下,結果將是:

row1: 2,2,1,'2012-07-05 12:18:58','msg2' 
row2: 4,1,3,'2012-07-05 12:19:10','msg4' 

回答

0
SELECT id, id_from, id_to, time, message 
FROM ( SELECT 
     FROM message 
     WHERE 1 IN (id_from, id_to) # 1 is user_id in this case 
     ORDER BY time DESC) AS h 
GROUP BY LEAST(id_from, id_to), GREATEST(id_from, id_to) 

解決方案獲得最後的發送和接收消息(沒有什麼要求儘管)

SELECT id, id_from, id_to, time, message 
FROM ( SELECT 
     FROM message 
     WHERE 1 IN (id_from, id_to) # 1 is user_id in this case 
     ORDER BY time DESC) AS h 
GROUP BY id_from, id_to 

應該這樣做,我猜。

我敢肯定,有「漂亮」的格式在捕捉到了這個

考慮:

SELECT id, 'from' AS type, id_from AS type_id, time, message 
FROM message 
WHERE id_to = 1 
ORDER BY time DESC 
LIMIT 1 
UNION ALL 
SELECT id, 'to', id_to, time, message 
FROM message 
WHERE id_from = 1 
ORDER BY time DESC 
LIMIT 1 

這將使你:

id type type_id time     message 
3 from 3  2012-07-05 12:19:04 msg3 
4 to 3  2012-07-05 12:19:10 msg4 
+0

我檢查,它不顯示正確,它返回行id3和id4 – 2012-07-05 10:41:14

+0

這就是我t應該這樣做,對吧? id3晚於id2。或者你想要每一次談話的最新消息? – 2012-07-05 10:46:40

+0

它應該返回id2和id4 – 2012-07-05 10:48:32

0

SELECT * FROM消息WHERE id_from = 1 OR id_to = 1?

+0

,將得到所有的消息該用戶的數據庫,我只想要每個用戶與user1交談的最後一條消息 – 2012-07-05 10:36:40