[英]MySQL: select last row of each pair
I have a little problem to solve, but I can't. 我有一点问题需要解决,但我不能。 I have the following chat
table: 我有以下chat
表:
id user friend msg date
----------------------------------------------------------------------
1 1 2 Hello Bob! 2014-07-04 01:00
2 1 2 How are you doing? 2014-07-04 01:01
3 2 1 I'm fine bro! 2014-07-04 02:30
4 1 3 Hey Mark :D 2014-07-04 02:31
5 3 1 Yo! 2014-07-04 02:32
6 4 1 Wassup?! 2014-07-04 07:00
I'm working on a PHP getInbox($uid)
method that returns an array of the last message of each pair (user and friend). 我正在研究PHP getInbox($uid)
方法,该方法返回每对(用户和朋友)的最后一条消息的数组。 I tried a SELECT
query with GROUP BY friend
, but it is incomplete. 我尝试使用GROUP BY friend
进行SELECT
查询,但它不完整。
SELECT * FROM `chat`
GROUP BY `friend`
WHERE `user` = $uid OR `friend` = $uid
The desired result is: 期望的结果是:
id user friend msg date
----------------------------------------------------------------------
3 2 1 I'm fine bro! 2014-07-04 02:30
5 3 1 Yo! 2014-07-04 02:32
6 4 1 Wassup?! 2014-07-04 07:00
I would appreciate a help! 我很感激帮助!
SELECT c.* FROM
chat c
JOIN
(SELECT
max(id) max_id,
(CASE WHEN user < friend THEN user ELSE friend END) user_a,
(CASE WHEN user < friend THEN friend ELSE user END) user_b
FROM chat
GROUP BY user_a, user_b) t1 ON t1.max_id = c.id
The case statements select (user,friend) in ascending order. case语句按升序选择(用户,朋友)。 For example, both (1,2) and (2,1) will be converted to (1,2). 例如,(1,2)和(2,1)都将转换为(1,2)。 An ordered pair uniquely identifies a conversation. 有序对唯一地标识对话。 Finally, the latest id is selected for each ordered pair and rows having those ids are displayed from the chat table. 最后,为每个有序对选择最新的id,并从聊天表中显示具有这些id的行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.