mysql选择id对的最后一个条目

时间:2012-07-05 10:28:46

标签: mysql

我想使用mysql实现一个消息系统进行存储。

这是表格:

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'

2 个答案:

答案 0 :(得分:0)

SELECT * FROM messages WHERE id_from = 1 OR id_to = 1?

答案 1 :(得分: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