Mysql> SELECT * from fruit;+----+--------+-------+| ID | Name | Price |+----+--------+-------+| 1 | Apple | 0 | | 2 | Banana | 0 | | 3 | Orange | 0 | | 4 | Mango | 0 | | 5 | pomelo | 0 |+----+--------+-------+5 rows in Set (0.00 sec)
The requirement is simple to change the value of the price column of the fruit table above to the value of the ID column, for example, the price of the first record is changed to 1 (corresponding ID).
At first, I was naïve to think:
1. Remove all records with PHP or any other
2. Then each record, individually modified
So there is a problem, the efficiency is not high, first of all, send the request, wait for the database to execute, and then the next record in the iteration.
And then a different method, which is the following statement:
mysql> Update fruit a set price = (select id from fruit b where a.id = b.ID);
In fact, the SQL statement written in particular, the meaning is not a problem, but MySQL does not support the change of a table, which is the table in the FROM clause.
Therefore, the above error message is as follows:
ERROR 1093 (HY000): You can ' t specify target table ' a ' for update in FROM clause
Announce the answer:
Update Price=id directly
mysql> update fruit set price=id; Query OK, 5 rows Affected (0.00 sec) rows Matched:5 changed:5 warnings:0mysql> select * FROM fruit;+----+---- ----+-------+| ID | Name | Price |+----+--------+-------+| 1 | Apple | 1 | | 2 | Banana | 2 | | 3 | Orange | 3 | | 4 | Mango | 4 | | 5 | pomelo | 5 |+----+--------+-------+5 rows in Set (0.00 sec)
First, in our usual update, insert, where filter, if the type of the value is a string type, we usually enclose it in quotation marks, but we don't enclose the field name.
In the above command, set Price=id, in fact, the ID is also the field name, not the value of the ID. When updated, the values are automatically taken out to update them.
MySQL bulk modifies the value of one column to the value of another field