Mysql SELECT inside UPDATE

≯℡__Kan透↙ 提交于 2019-11-30 15:37:41

问题


UPDATE forms SET

pos = (SELECT MIN(pos)-1 FROM forms)

WHERE id=$id

This doesn't work, error message:

**You can't specify target table 'form' for update in FROM clause**

I hope it's clear: I want to get the minimal element-1 from the same table and assign it to pos


回答1:


Consp is right that it's not supported. There's a workaround, however:

UPDATE forms SET
pos = (SELECT MIN(pos)-1 FROM (SELECT * FROM forms) AS x)
WHERE id=$id

A version that is probably faster:

UPDATE forms 
SET pos = (SELECT pos-1 FROM (SELECT MIN(pos) AS pos FROM forms) AS x)
where id=$id



回答2:


Your problem is stated plainly in the MySQL manual:

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

You'll want to use a transaction. Turn AutoCommit off, begin a transaction, then do a SELECT MIN(pos)-1 FROM forms FOR UPDATE, take that result, do the update with it, then commit your transaction.




回答3:


I think that you can not use a subquery inside an update statement, but any way there are workarounds for it ...

Here is a Quotation from the following site:

"dev.mysql.com"

“Currently, you cannot delete from a table and select from the same table in a sub-query ”




回答4:


You could also try:

START TRANSACTION;
SET @newMin := MIN(pos)-1 FROM forms;
UPDATE forms SET pos=@newMin WHERE id='$id';
COMMIT;


来源:https://stackoverflow.com/questions/1955988/mysql-select-inside-update

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