如何删除反转(m,n)< - > (n,m)有相同的信件吗?
Table
id1;id2;Letter
1;2;"A"
3;4;"B"
4;3;"B" -> row to be deleted or the one above(3;4;"B"), no matter which one
5;6;"C"
6;5;"C" -> row to be deleted or the one above(5;6;"C"), no matter which one
1;2;"B"
谢谢大家
答案 0 :(得分:1)
假设这种语法适用于PostgreSQL(我几年没有使用过它)
DELETE MT
FROM
My_Table MT
WHERE
MT.id1 > MT.id2 AND
EXISTS
(
SELECT *
FROM
My_Table MT2
WHERE
MT2.id1 = MT.id2 AND
MT2.id2 = MT.id1 AND
MT2.letter = MT.letter -- If this is also part of the requirement, otherwise you need logic on which row to keep
)
答案 1 :(得分:0)
执行此删除的另一种方法是:
delete
from table t
USING table t2
where t.id1 > t.id2
and t.id1 = t2.id2
and t.id2 = t2.id1
and t.Letter = t2.Letter;
您还应考虑添加两个验证约束和索引以防止此类情况再次发生:
alter table table add constraint chk_diff_ids CHECK (id1 != id2);
此CHECK CONSTRAINT
会避免id1 beeing insert等于id2 1;1;'A'
CREATE UNIQUE INDEX idx_reverse_value
ON table ( Letter, LEAST(id1,id2), GREATEST(id1,id2) );
此索引会阻止您想要删除时创建反转值,因此如果您有1,2,'B'
,则会阻止插入2,1,'B'
注意:table
是保留字,不应将其用作表名:)
在小提琴上看到它的工作:http://sqlfiddle.com/#!15/17f00/2