1. 程式人生 > 其它 >MySQL之多表關聯刪除/更新

MySQL之多表關聯刪除/更新

日常測試的時候,需要連線其他表而刪除某些髒資料,按照正常的查詢的寫法,會這樣寫刪除語句:

DELETE from `order` where id in (SELECT o.id from `order` o LEFT JOIN customer c on o.customer_id =c.id where o.customer_id is not null and c.id is null)

然後...... You can't specify target table 'order' for update in FROM clause

意思是:不能先select出同一表中的某些值,再update這個表,即不能依據某欄位值做判斷再來更新某欄位的值。

好吧~~~

百度研究一番這麼解決,可以多表連線進行刪除,這裡也疑惑了下,這個寫法為啥看書、看視訊的時候都不見介紹???

-- 刪除order表的資料
DELETE o from `order` o LEFT JOIN customer c on o.customer_id =c.id where o.customer_id is not null and c.id is null

-- 刪除customer表資料
DELETE c from `order` o LEFT JOIN customer c on o.customer_id =c.id where o.customer_id is not null and c.id is null

-- 同時刪除order、customer表資料
DELETE o,c from `order` o LEFT JOIN customer c on o.customer_id =c.id where o.customer_id is not null and c.id is null

順便也研究了下多表更新:

UPDATE wx_customer wc LEFT JOIN `order` o ON wc.id=o.wx_customer_id SET o.wx_customer_id = NULL,wc.customer_id = NULL,wc.relate_wx_id=NULL where wc.id = "937680";

這裡提一嘴:多表連線的更新,可以同時更新兩個表~

百度學習的時候,也有些大佬使用別名。。。。這個寫法日自己不怎麼使用,這裡就不貼上來了

總結規矩(不然有點不好記~):

不管是SELECT、DELETE 還是 UPDATE語句,都是在表這裡進行多表關聯操作,關聯。