按最后发送/接收的消息分组用户

时间:2014-01-25 21:54:20

标签: mysql sql

我有一个tbl:

CREATE TABLE if not exists tblA
(
id int(11) NOT NULL auto_increment ,
sender varchar(255),
receiver varchar(255),
 msg varchar(255),
 date timestamp,
  idmsg int(11)  ,
name varchar(255),
 PRIMARY KEY (id)
);




INSERT INTO tblA (sender, receiver,msg,date,name,idmsg ) VALUES
('1', '2', 'buzz ...','2011-08-21 14:11:09','Bb','1'),
('1', '2', 'test ...','2011-08-21 14:12:19','Bb','2'),
('1', '2', 'check ...','2011-08-21 14:13:29','Bb','3'),
('1', '1', 'test2 ...','2011-08-21 14:14:09','Aa','4'),
('2', '1', 'check2 ...','2011-08-21 14:15:09','Bb','5'),
('2', '1', 'test3 ...','2011-08-21 14:16:09','Bb','6'),
('1', '2', 'buzz ...','2011-08-21 14:17:09','Bb','7'),
('1', '2', 'test ...','2011-08-21 14:18:19','Bb','8'),
('1', '2', 'check ...','2011-08-21 14:19:29','Bb','9'),
('1', '1', 'test2 ...','2011-08-21 14:10:09','Aa','10'),
('3', '1', 'check2 ...','2011-08-21 14:21:09','Cc','11'),
('3', '1', 'test3 ...','2011-08-21 14:22:09','Cc','12'),
('1', '3', 'check ...','2011-08-21 14:26:29','Cc','13'),
('1', '3', 'test2 ...','2011-08-21 14:27:09','Cc','14'),
('1', '2', 'check3 ...','2011-08-21 14:23:09','Bb','15'),
('1', '4', 'test2 ...','2011-08-21 14:27:09','Dd','16'),
('1', '5', 'test2 ...','2011-08-21 14:27:09','Ee','17'),
('1', '7', 'test3 ...','2011-08-21 14:29:09','Gg','18');

如果1,2与2,1与max(日期)相同,如何获得与发送者,接收者不同的组。我已经尝试了http://www.sqlfiddle.com/#!2/b04cd5/29,但我没有得到确切的分组。

对于1,2或2,1组合,我得到14:11:+09,但正确答案是14:23。此外,它不检查反向,如检查1,2但不是2,1。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您似乎想要两个人之间的最新通信。我认为这样做你想要的:

select least(receiver, sender), greatest(receiver, sender),
       max(date),
       substring_index(group_concat(msg order by date separator '|'), '|', 1) as msg,
       substring_index(group_concat(idmsg order by date), ',', 1) as idmsg,
       substring_index(group_concat(name order by date separator '|'), '|', 1) as name
from tblA 
where '1' in (Receiver, Sender)
group by least(receiver, sender), greatest(receiver, sender);