按最新条目分组并过滤掉其他标准

时间:2013-05-19 07:15:33

标签: 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上使用附加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是错误的做法吗?

N.B。以下问题与此问题有些相似,例外,他们只处理一个标准。但在这里,我有两个(即用户可以是发送者或接收者)。这是我被困住的部分。

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

1 个答案:

答案 0 :(得分: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 ║
╚════╩════════╩══════════╩═══════════════════════════╝