我尝试从不同列和行的同一张表中联接或选择唯一行。唯一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行过滤掉。
这可能吗?
我会not exists
在id
以下条件下使用不等式条件:
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
。
cId | cPlayerA | 播放器 -:| -------:| -------: 1 | 2001 | 1001 3 | 4001 | 3001
辉煌。认为这是不可能的。非常感谢!
欢迎@PeterEricsson!如果我的回答正确回答了您的问题,请单击对号以接受它。谢谢。
做完了 很难找到..这是我的第一个问题...