Tritt während einer MySQL UPDATE-Abfrage der Fehler „Sie können in der FROM-Klausel keine Zieltabelle für die Aktualisierung angeben“ auf? Dies geschieht normalerweise, wenn Sie versuchen, in einer Unterabfrage auf die Tabelle zu verweisen, die aktualisiert wird. Schauen wir uns ein häufiges Szenario an:
<code class="language-sql">UPDATE pers P SET P.gehalt = P.gehalt * 1.05 WHERE (P.chefID IS NOT NULL OR gehalt <p>...This approach fails because MySQL prohibits referencing the updated table (pers) inside its own subquery.</p><h2>The Solution: Employing a Temporary Table (or JOIN)</h2><p>The solution involves creating a temporary representation of the table data to avoid directly referencing the `pers` table in the `WHERE` clause. Here's how:</p>UPDATE pers P SET P.gehalt = P.gehalt * 1.05 WHERE (P.chefID IS NOT NULL OR gehalt <p>This method uses a `SELECT` statement to create a temporary dataset. This allows the `WHERE` clause to reference the data without directly referencing the `pers` table being updated.</p><h2>Alternative: Using a JOIN</h2><p>Another effective method is to use a `JOIN` instead of a subquery:</p>UPDATE pers p INNER JOIN (SELECT chefID, gehalt FROM pers) AS temp ON p.chefID = temp.chefID AND p.gehalt = temp.gehalt SET p.gehalt = p.gehalt * 1.05 WHERE p.chefID IS NOT NULL OR p.gehalt <p>This approach achieves the same result by joining the `pers` table with itself (aliased as `temp`), thereby avoiding the restriction.</p><h2>Best Practices</h2><p>While using `SELECT *` simplifies the example, selecting only necessary columns and adding a `WHERE` clause to your subquery or `JOIN` significantly improves performance. Always prioritize efficiency in your database operations.</p></code>
Dies klärt das Problem und bietet alternative Lösungen. Denken Sie daran, für eine optimale Leistung nur die erforderlichen Spalten auszuwählen.
Das obige ist der detaillierte Inhalt vonWie löse ich den Fehler „Sie können die Zieltabelle für die Aktualisierung nicht in der FROM-Klausel angeben' in MySQL?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!