MySQL多表串連刪除問題,mysql刪除

來源:互聯網
上載者:User

MySQL多表串連刪除問題,mysql刪除

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 如果使用了別名的方式,那麼上下一致都用別名。

 

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.