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
The UPDATE from SELECT query structure is the main technique for performing these updates. An UPDATE query is used to change an existing row or rows in the database. UPDATE queries can change all tables' rows, or we can limit the update statement affects for certain rows with the help of the WHERE clause.
How do I update from a SELECT in MySQL? First, specify the name of the table that you want to update data after the UPDATE keyword. Second, specify which column you want to update and the new value in the SET clause. Third, specify which rows to be updated using a condition in the WHERE clause.
You can't. There's no convention in a SQL UPDATE statement for returning data. And vice versa -- a SELECT statement doesn't write information to a table.
UPDATE statements with a FROM clause are often used to update information in a table based on a table-valued parameter (TVP), or to update columns in a table in an AFTER trigger. For the scenario of update based on a TVP, see Implementing MERGE Functionality in a Natively Compiled Stored Procedure.
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
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.
You could also try:
START TRANSACTION;
SET @newMin := MIN(pos)-1 FROM forms;
UPDATE forms SET pos=@newMin WHERE id='$id';
COMMIT;
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 ”
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With