php - 按最新条目分组并使用附加条件过滤掉

标签 php mysql sql

表:

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

Returning the 'last' row of each 'group by' in MySQL

1st Row in Group By vs. Last Row

最佳答案

试试这个,

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/

相关文章:

php - 从平面 PHP SQL 表创建 JSON 树

java - 内部异常 : java. sql.SQLSyntaxErrorException:用户缺乏权限或未找到对象:SEQUENCE 但我使用 MySQL

mysql - Laravel 中数据库表的默认内容

mysql - SQL 仅选择列上具有最大值的行

使用 SUBSTRING 和 CONTAINS 的 SQL 查询

php - 在 PHP 中舍入到最大千、百等

php - Woocommerce 中特定产品的购物车批量折扣

php - mysqli_fetch_assoc()需要参数/调用成员函数bind_param()错误。如何获取并修复实际的mysql错误?

mysql - NetSuite 迁移

sql - 尽可能多地从 CLOB 到 VARCHAR2 选择数据,数据中包含多字节字符