Home > Database > Mysql Tutorial > Example analysis of MySQL implementing simultaneous query and update of the same table

Example analysis of MySQL implementing simultaneous query and update of the same table

黄舟
Release: 2017-09-20 11:23:38
Original
2282 people have browsed it

This article mainly introduces the method of simultaneously querying and updating the same table in MySQL database. Friends who need it can refer to it

In ordinary projects, we often encounter such problems: I need to The data is updated and queried simultaneously in Zhang Biao. For example: There is a table data as shown below. Now the update operation needs to be: update the name value of status=1 to the name value of id=2

Example analysis of MySQL implementing simultaneous query and update of the same table

Normally we The following statement will come to mind to achieve this requirement:

UPDATE tb_testSET NAME = ( SELECT NAME FROM tb_test WHERE id= 2)WHERE `status` = 1
Copy after login

The result is an error, the error message is: You can't specify target table 'tb_test' for update in FROM clause, cannot be in the same statement In update, select the same table. You cannot operate on the same table. If you think about it differently, it should be possible if it is not the same table. Therefore, the select result can be regarded as a temporary intermediate table, and the desired update-related data can be obtained from the intermediate table. Therefore, the above update statement can be changed to the following:

UPDATE tb_testSET NAME = (select name from ( SELECT NAME FROM tb_test WHERE id = 2) as t)WHERE `status` = 1
Copy after login

In this way, the operation in the question can be completed. The general process is: query the data with id=2 as the intermediate table t; query the set data from the t table; do the update operation so that you are not updating and selecting the same table in the same statement, because this is quite similar to Two tables are being operated, tb_test and intermediate table t. The final result is as shown below:

Example analysis of MySQL implementing simultaneous query and update of the same table

The above is the detailed content of Example analysis of MySQL implementing simultaneous query and update of the same table. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template