简体   繁体   English

MySQL选择ID对的最后一个条目

[英]mysql select last entry for ids pair

I want to implement a message system using mysql for storage. 我想使用mysql实现存储的消息系统。

This is the table: 这是表:

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 is the msg sender, id_to is the msg receiver . id_from是味精发送方,id_to是味精接收方。

Below inserting 4 messages for testing purposes: 下面插入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');

What I want to do and not succeeding, is building a query that fetches the last sent or received message for each pair (id_from, id_to) for a specific user. 我想做的但没有成功的事,是建立一个查询,以为特定用户获取每对消息对(id_from,id_to)的最后发送或接收的消息。 In this case, the result would be: 在这种情况下,结果将是:

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

选择* FROM消息,其中id_from = 1或id_to = 1?

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)

Solution for gaining the last sent and received message (not what's asked for though) 获取最后发送和接收的消息的解决方案 (虽然不是要求的内容)

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

Should do it I guess. 我猜应该这样做。

I'm sure there are "prettier" format to capture this in. 我确定有“更漂亮”的格式可以捕捉到它。

Consider: 考虑:

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

This would give you: 这将为您提供:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM