温馨提示:本文翻译自stackoverflow.com,查看原文请点击:mysql - Join two columns with IDs on different rows
mysql

mysql - 将两列ID不同的行合并在一起

发布于 2020-03-27 15:52:47

问题描述

我尝试从不同列和行的同一张表中联接或选择唯一行。唯一ID在列cPlayerA和cPlayerB中都存在。该表可以动态增长,我无法对SQL进行硬编码。

表结构和数据

CREATE TABLE tJoinTwoColumn(
cId int(11) NOT NULL AUTO_INCREMENT,
cPlayerA int(10) DEFAULT NULL,
cPlayerB int(10) DEFAULT NULL,
PRIMARY KEY (cId)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

#insert data
INSERT INTO tJoinTwoColumn (cId,cPlayerA,cPlayerB) VALUES (1,2001,1001);
INSERT INTO tJoinTwoColumn (cId,cPlayerA,cPlayerB) VALUES (2,1001,2001);
INSERT INTO tJoinTwoColumn (cId,cPlayerA,cPlayerB) VALUES (3,4001,3001);
INSERT INTO tJoinTwoColumn (cId,cPlayerA,cPlayerB) VALUES (4,3001,4001);

select * from tJoinTwoColumn;

返回数据

显示选择了什么,我需要过滤掉什么

显示选择了什么,我需要过滤掉什么

我试过的代码

select distinct t1.cPlayerA , t1.cPlayerB  from tJoinTwoColumn t1
join  tJoinTwoColumn t2 on t1.cPlayerA = t2.cPlayerB
group by t1.cPlayerA , t1.cPlayerB;

但是在上面的示例中我只想返回2行时,它返回4行,我希望在选择中将第2行和第4行过滤掉。

这可能吗?

查看更多

查看更多

提问者
Peter Ericsson
被浏览
15
GMB 2020-01-31 16:28

我会not existsid以下条件下使用不等式条件

select t.*
from tJoinTwoColumn t
where not exists (
    select 1
    from tJoinTwoColumn t1
    where 
        least(t1.cPlayerA, t1.cPlayerB) = least(t.cPlayerA, t.cPlayerB)
        and greatest(t1.cPlayerA, t1.cPlayerB) = greatest(t.cPlayerA, t.cPlayerB)
        and t1.cId < t.cId
)

这样会过滤掉真实的重复记录和“镜像”记录,从而保留最小的记录id

DB Fiddle上的演示

cId | cPlayerA | 播放器
-:| -------:| -------:
  1 | 2001 | 1001
  3 | 4001 | 3001