Home > Database > Mysql Tutorial > body text

How to Fix 'Table Specified Twice' Error in MySQL UPDATE Queries?

Susan Sarandon
Release: 2024-11-12 06:46:01
Original
878 people have browsed it

How to Fix

Table Specified Twice: Resolving Update Conflict in MySQL

When attempting to update a table that appears as both a target for update and a separate data source, MySQL may raise the error "Table 'table_name' is specified twice, both as a target for 'UPDATE' and as a separate source for data." This issue arises when you reference the same table multiple times in your query.

Specifically, this error message indicates that the manager table is being used both as the target table for the UPDATE operation and as a data source for selecting data from the branch_master table. This double reference can confuse MySQL.

Solution

The solution is to isolate the table in your data source into a derived table, which is a temporary table created on the fly to hold the data from the original table. By doing this, you can avoid ambiguity in your query.

Replace the following line in your query:

FROM manager AS m2
Copy after login

with:

FROM (select * from manager) AS m2
Copy after login

This will create a derived table called m2 that contains all the data from the original manager table.

Updated Query

Here is the updated query that will resolve the table conflict error:

UPDATE manager
SET status = 'Y'
WHERE branch_id IN
(
  select branch_id
  FROM (select * from manager) AS m2
  WHERE (branch_id, year) IN
  (
    SELECT branch_id, year
    FROM branch_master
    WHERE type = 'finance'
  )
);
Copy after login

By using a derived table, you can ensure that the manager table is referenced only once in your query, preventing MySQL from encountering the "Table specified twice" error.

The above is the detailed content of How to Fix 'Table Specified Twice' Error in MySQL UPDATE Queries?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template