简体   繁体   中英

mysql select last entry for ids pair

I want to implement a message system using mysql for storage.

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 .

Below inserting 4 messages for testing purposes:

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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