MySQL:选择每对的最后一行

时间:2014-07-04 16:40:46

标签: php mysql

我有一点问题要解决,但我不能。我有以下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

我正在开发一个PHP getInbox($uid)方法,该方法返回每对(用户和朋友)的最后一条消息的数组。我尝试使用SELECT进行GROUP BY friend查询,但不完整。

SELECT * FROM `chat`
GROUP BY `friend` 
WHERE `user` = $uid OR `friend` = $uid

期望的结果是:

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

我很感激帮助!

1 个答案:

答案 0 :(得分:3)

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

案例陈述按升序选择(用户,朋友)。例如,(1,2)和(2,1)都将转换为(1,2)。有序对唯一地标识对话。最后,为每个有序对选择最新的ID,并从聊天表中显示具有这些ID的行。