如何删除有点重复行?

问题描述 投票:0回答:1

我有这样的关系,它看起来像这样

CREATE TABLE table_name (
letter1 text,
letter2 text)

INSERT INTO table_name (letter1, letter2) VALUES ('A', 'B')
INSERT INTO table_name (letter1, letter2) VALUES ('B', 'A')

letter1     letter2
--------------------
A               B
B               A

不过,我想删除重复的组合,使得(A,B)=(B,A),这样,我就只剩下一方。

我现在很迷茫。我试图用选择符合条件,我也尝试创建另一个表进行比较,然后使用选择,但我迷路了。

sql sqlite
1个回答
1
投票

你可以做:

delete t
    where l1 > l2 and
          exists (select 1
                  from t t2
                  where t2.l2 = t1.l1 and t2.l1 = t1.l2
                 );

如果你只是想选择的不同对,你可以这样做:

select l1, l2
from t
where l1 < l2
union all  -- or union if you need to remove duplicates
select l2, l1
from t
where l2 > 1 and
      not exists (select 1
                      from t t2
                      where t2.l2 = t1.l1 and t2.l1 = t1.l2
                 );
© www.soinside.com 2019 - 2024. All rights reserved.