sql查询组由特定结果作为两个字段值的组合值

时间:2012-10-26 08:39:40

标签: mysql sql

我的留言表包含两个字段senderidrecipientid。我需要列出所有邮件,但senderidrecipientid中的值组合不需要重复。

例如,如果senderid = 4recipientid = 2,我只需要一个组合值;要么是4,2,要么是2,4。

任何人都可以帮我这么做吗?

提前致谢;)

3 个答案:

答案 0 :(得分:0)

select
    message,
    case when senderid < recipientid then recipientid else senderid end,
    case when senderid < recipientid then senderid else recipientid end
from m
group by
    message,
    case when senderid < recipientid then recipientid else senderid end,
    case when senderid < recipientid then senderid else recipientid end

答案 1 :(得分:0)

select *
from myTable a
where not exists
(
    select top 1 1 
    from myTable b
    where a.senderId = b.receiverId
    and a.receiverId = b.senderId
    and a.senderId < b.senderId
)

答案 2 :(得分:0)

想法很简单,只需确保发件人/收件人ID的连接方式使得较小的ID位于较大的ID前面。

select
  pair, count(*) 
from 
  (select if(senderid<recipientid, concat(senderid, ',', recipientid), concat(recipientid,',',senderid)) as pair from messages) pairs
group by pair;

注意这种选择的表现。也许你想在插入记录时创建一个额外的列来存储对值,并将列编入索引。