卡在mysql查询中

时间:2016-01-06 11:44:40

标签: php mysql

我想计算单个用户从另一个用户发送和接收的最大消息数。我不明白如何实现这一点。

Example for 3 messages exchanged:
[1] John(1472) msg Jane
    Jane msg John(1472)
[2] John(1472) msg Jane
    Jane msg John(1472)
[3] John(1472) msg Jane

OR

[1] John(1472) msg Jane
    Jane msg John(1472)
[2] John(1472) msg Jane
    Jane msg John(1472)
[3] John(1472) msg Jane
    Jane msg John(1472)

OR

[1] John(1472) msg Jane
    John(1472) msg Jane
    John(1472) msg Jane
    Jane msg John(1472)
[2] John(1472) msg Jane
    John(1472) msg Jane
    Jane msg John(1472)
    Jane msg John(1472)
[3] John(1472) msg Jane
    Jane msg John(1472)

以上所有示例都将在这两个用户之间交换3条消息。我的表格结构如下:http://sqlfiddle.com/#!9/f84f17/1

每当用户向另一个用户发送消息时,我们在邮箱表中插入两行,其中包含不同的senderid,receiverid,所有者和文件夹(收件箱/已发送)。

1 个答案:

答案 0 :(得分:1)

要选择用户与任何其他用户之间交换的最大数量的消息,您可以按对等分组,按计数排序,然后选择第一个结果:

SELECT count(*), if(owner=senderid, recipientid, senderid) as peer FROM mailbox
WHERE owner = 1472
GROUP BY 2
ORDER BY 1 desc
LIMIT 1
相关问题