表:
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
,因为那样它只会包含用户发送的最后一个条目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,但它可以是任何用户。
简单来说:,
I want to retrieve the last message in a conversation between A and B, regardless of who said it.
这里使用GROUP BY
是错误的方法吗?
注意下面的问题与这个问题有些相似除了它们只处理一个标准。但在这里,我有两个(即用户可以是发送者或接收者)。这是我陷入困境的部分。
Retrieving the last record in each group
MySQL - Control which row is returned by a group by
最佳答案
试试这个,
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 ║
╚════╩════════╩══════════╩═══════════════════════════╝
关于php - 按最新条目分组并使用附加条件过滤掉,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16632302/