Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql SELECT inside UPDATE

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

like image 818
Dan Avatar asked Dec 23 '09 23:12

Dan


People also ask

Can we use SELECT in UPDATE?

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 a SELECT statement in MySQL?

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.

Can you use the UPDATE and SELECT in one SQL statement?

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.

Can I use from clause in UPDATE?

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.


4 Answers

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
like image 91
Mark Byers Avatar answered Oct 16 '22 05:10

Mark Byers


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.

like image 45
Conspicuous Compiler Avatar answered Oct 16 '22 03:10

Conspicuous Compiler


You could also try:

START TRANSACTION;
SET @newMin := MIN(pos)-1 FROM forms;
UPDATE forms SET pos=@newMin WHERE id='$id';
COMMIT;
like image 41
cmptrgeekken Avatar answered Oct 16 '22 04:10

cmptrgeekken


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 ”

like image 21
RAO Avatar answered Oct 16 '22 04:10

RAO