Home  >  Article  >  Database  >  Why Does MySQL Throw "Table Specified Twice" Error When Updating a Table Using a Subquery?

Why Does MySQL Throw "Table Specified Twice" Error When Updating a Table Using a Subquery?

Susan Sarandon
Susan SarandonOriginal
2024-11-15 02:40:02435browse

Why Does MySQL Throw

MySQL Error: Table Specified Twice in UPDATE and Source

When attempting to update the manager table using the provided SQL query, MySQL encounters an error: "Table 'm1' is specified twice, both as a target for 'UPDATE' and as a separate source for data." This error occurs due to the table manager being referenced twice in the subquery.

The issue can be resolved by modifying the subquery to select from a derived table. Instead of using the alias m2 directly, the query should create a temporary table using the SELECT statement, and then select from that temporary table. The modified query below achieves this:

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'
  )
);

By using a derived table, MySQL can properly differentiate between the manager table used in the UPDATE statement and the manager table referenced in the subquery. This eliminates the confusion that led to the error message.

The above is the detailed content of Why Does MySQL Throw "Table Specified Twice" Error When Updating a Table Using a Subquery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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