在下面,您将找到用于创建我的表的 sql 代码以及插入的数据
CREATE TABLE TEST (A varchar(4), B varchar(4));
INSERT INTO TEST (ID,A,B) VALUES ('1','d','a');
INSERT INTO TEST (ID,A,B) VALUES ('1','c','a');
INSERT INTO TEST (ID,A,B) VALUES ('1','b','a');
INSERT INTO TEST (ID,A,B) VALUES ('1','a','xxx');
INSERT INTO TEST (ID,A,B) VALUES ('1','a','d');
INSERT INTO TEST (ID,A,B) VALUES ('1','a','c');
INSERT INTO TEST (ID,A,B) VALUES ('1','a','b');
INSERT INTO TEST (ID,A,B) VALUES ('2','g','a');
INSERT INTO TEST (ID,A,B) VALUES ('2','a','g');
INSERT INTO TEST (ID,A,B) VALUES ('3','f','b');
INSERT INTO TEST (ID,A,B) VALUES ('3','b','f');
INSERT INTO TEST (ID,A,B) VALUES ('4','s','r');
INSERT INTO TEST (ID,A,B) VALUES ('4','r','s');
INSERT INTO TEST (ID,A,B) VALUES ('5','r','t');
INSERT INTO TEST (ID,A,B) VALUES ('7','h','g');
如前所述,使用此查询:
select distinct tab1.ID,
( case when tab1.A < tab1.B then tab1.A else tab1.B end ) as A,
( case when tab1.A > tab1.B then tab1.A else tab1.B end) as B
from TEST tab1, TEST tab2
...我得到了想要的结果:
ID A B
-- -- --
1 a b
1 a c
1 a d
1 a xxx
2 a g
3 b f
4 r s
5 r t
7 g h
抱歉,伙计们,也许我在这里想念一些东西,但您的解决方案似乎仍然无法按预期工作。
@fthiella:我测试了您的解决方案:
SELECT tab1.*
FROM TEST tab1 LEFT JOIN TEST tab2 on tab1.B=tab2.A
WHERE tab1.A<tab1.B OR tab2.A is null
结果(a/b
重复,g/h
缺失):
ID A B
-- -- --
1 a b
1 a b
1 a c
1 a xxx
2 a g
3 b f
4 r s
5 r t
@wildplasser:看来这个解决方案也不起作用
SELECT * FROM TEST t
WHERE EXISTS (
SELECT * FROM TEST x
WHERE x.a = t.b AND x.b = t.a
AND x.a > x.b -- tie breaker
);
结果(a/xxx
并且r/t
丢失):
ID A B
-- -- --
1 a b
1 a c
1 a d
2 a g
3 b f
4 r s