桌子:
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 BY
on 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 下面的问题与这个问题有些相似,只是它们只处理一个标准。但是在这里,我有两个(即用户可以是发送者或接收者)。这是我被困在的部分。