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语句,都是在表这里进行多表关联操作,关联。