Home > Database > Mysql Tutorial > How to Correctly Use Subqueries in MySQL DELETE Statements?

How to Correctly Use Subqueries in MySQL DELETE Statements?

Patricia Arquette
Release: 2025-01-10 17:56:42
Original
499 people have browsed it

How to Correctly Use Subqueries in MySQL DELETE Statements?

Subquery conditions in MySQL DELETE statement

You may encounter syntax errors when using a subquery as a condition to delete rows from a table. To solve this problem, you need to consider the limitations of using subqueries in DELETE operations.

In MySQL, you cannot use subqueries directly in the WHERE clause of a DELETE statement. However, there is a clever way around this limitation. By using an additional subquery to include the original subquery, the delete operation can be performed successfully.

For example, 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>
Copy after login

will produce a syntax error. However, by wrapping the subquery in another subquery like 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>
Copy after login

The delete operation can be performed successfully. Remember that the enclosing subquery should be named, as shown by the "x" alias in the example.

The above is the detailed content of How to Correctly Use Subqueries in MySQL DELETE Statements?. 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