正常情况下delete from后面直接加表名加where条件即可,但假如有种特殊情况,需要做联名筛选才能确定哪些记录需要删除,要怎么做呢。
比如下面例子,如果要删除40天以前的推送token,表设计时又没有记录token写入的时间,此时就需要跟活跃用户名关联,写成:
delete from fb_token fb left join user_active ua on fb.uid=ua.uid where ua.timestamp < date_sub(now(), INTERVAL 40 day);
此时MySQL会报错:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'left join user_active ...
说SQL语法不正确,一查果然不对,当单表操作时,delete后面不需要接目标对象,而当多表操作时,delete后面需要接目标对象,正确写法为:
delete fb from fb_token fb left join user_active ua on fb.uid=ua.uid where ua.timestamp < date_sub(now(), INTERVAL 40 day);