Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用于删除/标识表中交叉链接数据的SQL查询_Sql_Tsql - Fatal编程技术网

用于删除/标识表中交叉链接数据的SQL查询

用于删除/标识表中交叉链接数据的SQL查询,sql,tsql,Sql,Tsql,我有一个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 cro

我有一个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

我想写一个sql查询来实现这一点。有人知道我怎样才能做到这一点吗

SELECT A.* FROM test A LEFT JOIN test B
ON A.column1 = B.column2 AND A.column2 = B.column
WHERE B.column IS NULL;
这应该可以,假设您同意,2,2之类的东西也被排除在外。

试试这个:

解释 CTE表返回一侧的所有成对行。 通过NOT EXISTS,它返回所有未配对的行

如果将其中c1=minc和c2=maxc的条件更改为其中c2=minc和c1=maxc将得到对的另一侧

如果要删除这些对的一侧,请使用delete FROM T WHERE EXISTS而不是NOT EXISTS


有一些不同的方法可以获得成对的行。

您使用的是哪种DBMS?
SELECT A.* FROM test A LEFT JOIN test B
ON A.column1 = B.column2 AND A.column2 = B.column
WHERE B.column IS NULL;
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
)