2012-07-02 52 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)