Home > Database > Mysql Tutorial > How to Solve MySQL Error 1093: 'You can't specify target table for update in FROM clause'?

How to Solve MySQL Error 1093: 'You can't specify target table for update in FROM clause'?

DDD
Release: 2025-01-22 19:42:10
Original
198 people have browsed it

How to Solve MySQL Error 1093:

MySQL Error 1093: Update query limit

Question:

When trying to update the pers table using a subquery, I get the error "You can't specify target table for update in FROM clause" (Error 1093).

Query:

<code class="language-sql">UPDATE pers P
SET P.gehalt = P.gehalt * 1.05
WHERE (P.chefID IS NOT NULL
OR gehalt <p><strong>原因:</strong></p><p>MySQL 不允许在子查询中引用正在更新的同一表。</p><p><strong>解决方案:</strong></p><p>要解决此问题,请将外部表引用(pers)在子查询中用嵌套子查询括起来:</p>
```sql
UPDATE pers P
SET P.gehalt = P.gehalt * 1.05
WHERE (P.chefID IS NOT NULL
OR gehalt <p><strong>说明:</strong></p><p>通过使用 `SELECT * FROM pers` 创建嵌套子查询,我们隐式地创建了一个临时表,可以在子查询中引用它,而不会违反 MySQL 的限制。这允许我们使用所需的条件更新 `pers` 表。</p></code>
Copy after login

Improved solution (clearer example):

To illustrate the solution more clearly, a JOIN statement can be used instead of a subquery:

<code class="language-sql">UPDATE pers p
INNER JOIN (SELECT chefID, gehalt FROM pers) AS subquery ON p.chefID = subquery.chefID AND p.gehalt = subquery.gehalt
SET p.gehalt = p.gehalt * 1.05
WHERE p.chefID IS NOT NULL OR p.gehalt < ...;</code>
Copy after login

This method avoids directly referencing the pers table in the subquery, thus bypassing MySQL limitations. subquery Acts as a temporary table, allowing safe update operations. Note that you need to supplement the WHERE part based on the actual ... condition.

The above is the detailed content of How to Solve MySQL Error 1093: 'You can't specify target table for update in FROM clause'?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template