How to use subquery in delete/update query in mysql

三世轮回 提交于 2019-12-13 07:05:11

问题


I am using a mysql 5.0.77 database using the query:

Delete from IPADDRESS
where visitdate Not in (SELECT max(visitdate) FROM IPADDRESS WHERE USERNAME='MGSH0002') 
and USERNAME='MGSH0002' 

I am getting this error when executed:

You can't specify target table IPADDRESS for update in from clause


回答1:


Certainly not the best solution but for your problem this will do the trick:

delete i1 from
  IPADDRESS i1,
  IPADDRESS i2
where
  i1.username = i2.username
  and i1.username = 'MGSH0002'
  and i1.visitdate < i2.visitdate

An alternative and much more smarter solution is the following statement:

delete i1 from
  IPADDRESS i1,
  (select max(visitdate) visitdate from IPADDRESS where username = 'MGSH0002') temp
where
  i1.username = 'MGSH0002'
  and i1.visitdate < temp.visitdate



回答2:


You can't, unfortunately MySql doesn't allow this.

Currently, you cannot update a table and select from the same table in a subquery.

From:

http://dev.mysql.com/doc/refman/5.0/en/update.html



来源:https://stackoverflow.com/questions/9907484/how-to-use-subquery-in-delete-update-query-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!