MySQL DELETE statement using subquery as condition
In MySQL, the DELETE statement allows you to delete rows from a table based on specified conditions. A common situation is to use subqueries to define conditions. However, it can be frustrating to encounter syntax errors when trying to do this.
A user tried to delete rows from the term_hierarchy table using the following query:
<code class="language-sql">DELETE FROM term_hierarchy AS th WHERE th.parent = 1015 AND th.tid IN ( SELECT DISTINCT(th1.tid) FROM term_hierarchy AS th1 INNER JOIN term_hierarchy AS th2 ON (th1.tid = th2.tid AND th2.parent != 1015) WHERE th1.parent = 1015 );</code>
However, this resulted in the following error:
<code>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS th WHERE th.parent = 1015 AND th.tid IN ( SELECT DISTINCT(th1.tid) FROM ter' at line 1</code>
The problem here is a limitation of MySQL: the table being deleted (term_hierarchy in this case) is not allowed to be used in a subquery of the condition. This restriction prevents you from self-referencing tables in DELETE statements.
Solution:
To work around this limitation, you can use a nested subquery that references the subquery without including the table to be deleted. The following modified query demonstrates this:
<code class="language-sql">DELETE e.* FROM tableE e WHERE id IN (SELECT id FROM (SELECT id FROM tableE WHERE arg = 1 AND foo = 'bar') x);</code>
By wrapping a subquery in another subquery (named x in this example), MySQL can perform delete operations without violating the self-reference restriction.
The above is the detailed content of How to Correctly Use Subqueries in MySQL DELETE Statements to Avoid Syntax Errors?. For more information, please follow other related articles on the PHP Chinese website!