Mysql组由2列使用OR

时间:2015-11-04 17:36:06

标签: mysql database relation

我有一张表示对话的消息表:

| sender     | bigint(20) unsigned | NO   | MUL | NULL    |       |
| recipient  | bigint(20) unsigned | NO   | MUL | NULL    |       |
| text       | text                | NO   |     | NULL    |       |

每行都有发件人,收件人和邮件文本。

我想运行一个查询,返回每个对话中的所有对话和消息数。

所以如果数据如下:

1,2,Hello
2,1,Bye
1,3,Hi

我想知道1和2之间的对话有2条消息,1和3之间的对话有1条消息

所以我需要做一些像

这样的事情
SELECT count(*), SET OF(sender, recipient) from messages group by ( sender OR recipient )

但显然,这不起作用。有什么类似的我可以做

2 个答案:

答案 0 :(得分:3)

您可以通过先选择(发件人,收件人)的最小值,然后选择(发件人,收件人)的最大值并按其分组来重新排列配对,以获得每对的计数。试试这个:

SELECT LEAST(sender, recipient) AS firstPerson, GREATEST(sender, recipient) AS secondPerson, COUNT(*) AS numMessages
FROM myTable
GROUP BY LEAST(sender, recipient), GREATEST(sender, recipient);

答案 1 :(得分:0)

SELECT sender_reciever,COUNT(*) AS message_count
    FROM
    (SELECT (IF(sender>recipient,CONCAT(sender,'_',recipient),CONCAT(recipient,'_',sender))) AS sender_reciever
    FROM
    message_table) T
    GROUP BY sender_reciever

希望这有帮助