SQL删除行,其中一个值与DIFFERENT列中的值匹配

时间:2016-09-12 15:50:06

标签: sql

如果特定x值与同一表中任何行中的y值匹配,我想删除一行。

前:

| x | y |  
| 4 | 2 |  
| 2 | 6 |  
| 8 | 1 |  
| 3 | 1 |  
| 7 | 8 |  
| 9 | 5 |

会变成:

| x | y |    
| 4 | 2 |  
| 3 | 1 |  
| 7 | 8 |  
| 9 | 5 |

3 个答案:

答案 0 :(得分:2)

使用EXISTS

Delete from 
yourtable where exists (select 1 from tab b where b.y =yourtable.x) 

答案 1 :(得分:1)

如果您的数据库允许,可以使用自联接:

DELETE FROM foo AS xside
LEFT JOIN foo AS yside ON xside.y = yside.x

答案 2 :(得分:1)

Delete from tab where x in ( select y from tab)

替代版本以计算y列中的空值。

Delete from tab t where exists ( select 1 from tab ta where ta.y = t.x)