2012-07-02 51 views
0

我有2个表。SQL命令来检查ID差异

我如何知道一个表中的ID而不是另一个表上的ID?我将如何实现这一目标?

然后我想删除所有这样的ID。

回答

3

这是非常简单的:

delete from t1 
using table1 as t1 
left outer join table2 as t2 
on t1.id = t2.id 
where t2.id is null 

值得一提的是连接比快的子查询。

+0

同意,您的解决方案是更好的。如果table2有大量的行,做一个NOT IN(子查询)将是一场噩梦。 –

+0

是的,虽然我记得MySQL的怪癖(有没有很多?)其中你不能离开外部联接删除没有'使用'条款,所以它看起来有点毛病。尽管如此,还是比依赖子查询更好。 – syrion

+0

为什么加入比子查询更快? –

3

使用此查询:

delete from TABLE_A where ID not in (select ID from TABLE_B) 
1

使用此查询:

delete from t1 
where id not in 
(select t2.id from t2)