我有一个SQL DB表ABC,其中有两列,即column1和column2。
在这张表中,我有一些类似的数据。
column1 column2
-------------------
1 2
1 7
2 1
3 4
7 1
4 3
现在,我必须从这个表中删除相互交叉链接的数据。例如
(1,2) are cross linked to (2,1)
(1,7) are cross linked to (7,1)
(3,4) are cross linked to (4,3)
所以,我需要从这对值中删除一个。我的最终输出应该是:
column1 column2
-------------------
1 2
1 7
3 4
或
column1 column2
-------------------
2 1
4 3
7 1
我想写一个sql查询来实现这一点。有人知道我是怎么做到的吗?
试试这个:SQLFIDDLE
with pairs as (select
case when c1< c2 then c1 else c2 end as minc,
case when c1< c2 then c2 else c1 end as maxc
from t
group by
case when c1< c2 then c1 else c2 end ,
case when c1< c2 then c2 else c1 end
having count(*) >1)
select *
from t
where not exists
(select * from pairs
where c1= minc and c2= maxc
)
解释
- CTE表返回一侧的所有成对行
通过
NOT EXISTS
返回所有未配对的行如果将
where c1= minc and c2= maxc
的条件更改为where c2= minc and c1= maxc
,则会得到对的对边。如果要删除这些对的一侧,请使用
DELETE FROM T WHERE EXISTS
而不是NOT EXISTS
有一些不同的方法可以获得成对的行。
SELECT A.* FROM test A LEFT JOIN test B
ON A.column1 = B.column2 AND A.column2 = B.column
WHERE B.column IS NULL;
这应该是有效的,假设你的OK(2,2)也被排除在外。