0

桌子:

id    sender    receiver        message
 1      14        16            1st message from 14 to 16
 2      16        14            1st message from 16 to 14
 3      16        14            2nd message from 16 to 14
 4      14        16            2nd message from 14 to 16
 5      15        14            1st message from 15 to 14
 6      15        14            2nd message from 15 to 14
 7      14        16            3rd message from 14 to 16
 8      14        16            4th message from 14 to 16
 9      14        15            1st message from 14 to 15
10      14        15            2nd message from 14 to 15

现在,我在这里要做的是将消息分组为一个用户(作为接收者),但问题是我想要最新的条目,而不管是谁发送了消息

尝试1:

SELECT c2. *
FROM (

SELECT max( id ) `id`
FROM tbl_msg
GROUP BY `sender`
)c1
INNER JOIN tbl_msg c2 ON c1.id = c2.id
WHERE `receiver` =14
GROUP BY `sender`

结果:

id    sender    receiver        message
 6      15        14            2nd message from 15 to 14
 3      16        14            2nd message from 16 to 14

这里的结果是每条最后的消息都发送给用户 14。它显然不会包含用户 14发送的消息。

同样,我不能使用附加GROUP BYon receiver,因为那样它只会包括用户 14发送的最后一个条目。

预期输出:

id    sender    receiver        message
10      14        15            2nd message from 14 to 15
 8      14        16            4th message from 14 to 16

现在在上面,sender两个条目都是 14,但它可以是任何用户。

简单来说: ,

我想检索 A 和 B 之间对话中的最后一条消息,不管是谁说的。

在这里使用GROUP BY错误的方法吗?

NB 下面的问题这个问题有些相似,只是它们只处理一个标准。但是在这里,我有两个(即用户可以是发送者或接收者)。这是我被困在的部分。

检索每个组中的最后一条记录

MySQL - 控制组返回哪一行

返回 MySQL 中每个“分组依据”的“最后”行

分组依据中的第一行与最后一行

4

1 回答 1

2

试试这个,

SELECT  *
FROM    TableName
WHERE   (LEAST(sender, receiver),GREATEST(sender, receiver), id) 
        IN (
                SELECT  LEAST(sender, receiver) AS x,
                        GREATEST(sender, receiver) AS y,
                        MAX(id) AS max_ID
                FROM    TableName
                GROUP   BY x, y
            )

输出

╔════╦════════╦══════════╦═══════════════════════════╗
║ ID ║ SENDER ║ RECEIVER ║          MESSAGE          ║
╠════╬════════╬══════════╬═══════════════════════════╣
║  8 ║     14 ║       16 ║ 4th message from 14 to 16 ║
║ 10 ║     14 ║       15 ║ 2nd message from 14 to 15 ║
╚════╩════════╩══════════╩═══════════════════════════╝
于 2013-05-19T07:34:28.740 回答