DELETE是一個蠻慎重的SQL操作,一般來說這樣刪除操作都需要謹慎小心,以免造成不必要的損失。
DELETE有下面這幾種情況:
? delete from t1 where 條件
? delete t1 from t1 where 條件
? delete t1 from t1,t2 where 條件
? delete t1,t2 from t1,t2 where 條件
簡單地說就是delete語句是無法進行多表刪除數據操作,不過可以通過建立級聯刪除,在兩個表之間建立級聯刪除關系,來實現刪除一個表的數據時,同時刪除另一個表中相關的數據。
舉例說明:
1) 從數據表MV中把那些id值在數據表Track裡有匹配的記錄全刪除掉
DELETE MV
FROM MV,Track
WHERE Track.trkid=MV.mvid
等同於
DELETE FROM MV
USING MV,Track
WHERE Track.trkid=MV.mvid
2) 從數據表MV裡在數據表Track裡沒有匹配的記錄查找出來並刪除掉
DELETE MV
FROM MV
LEFT JOIN Track
ON MV.mvid=Track.trkid
WHERE Track.trkid IS NULL
等同於
DELETE FROM MV
USING MV
LEFT JOIN Track
ON MV.mvid=Track.trkid
WHERE Track.trkid IS NULL
3) 從兩個表中找出相同記錄的數據並把兩個表中的數據都刪除掉
DELETE MV,Track
FROM MV
LEFT JOIN Track
ON MV.mvid=Track.trkid
WHERE MV.mvid=1
用別名的方式:
DELETE t1,t2
FROM MV t1
LEFT JOIN Track t2
ON t1.mvid=t2.trkid
WHERE t1.mvid=2
※ 以下兩種情況會報錯:
delete MV,Track
from MV as t1
left join Track as t2
on t1.mvid=t2.trkid
where t1.mvid=5
***********************
DELETE t1,t2
FROM MV t1
LEFT JOIN Track t2
ON t1.mvid=t2.trkid
WHERE MV.mvid=2
so 如果使用了別名的方式,那麼上下一致都用別名。