Home > Database > Mysql Tutorial > How to Efficiently Delete Non-Unique Rows in MySQL 5.0?

How to Efficiently Delete Non-Unique Rows in MySQL 5.0?

Mary-Kate Olsen
Release: 2024-12-27 11:01:08
Original
653 people have browsed it

How to Efficiently Delete Non-Unique Rows in MySQL 5.0?

Deleting Non-Unique Rows in MySQL Using a Select Statement

The provided query syntax

DELETE FROM posts where> attempts to delete rows that do not have unique IDs from the posts table. However, this syntax is incompatible with MySQL 5.0.</p>
<p><strong>Rewriting the Query</strong></p>
<p>To make the query compatible with MySQL 5.0, it should be rewritten as follows:</p>
<p>`<pre class="brush:php;toolbar:false">DELETE FROM posts WHERE id IN (</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">SELECT id FROM posts GROUP BY id HAVING ( COUNT(id) > 1 )
Copy after login

)
`

Understanding the Revised Query

The revised query uses the IN operator to compare the id column of the posts table with the result set of the subquery. The subquery retrieves the IDs of rows that have more than one occurrence in the posts table, indicating non-unique IDs. By using the IN operator, the query selects only the rows with non-unique IDs for deletion.

Additional Considerations

As mentioned in the answer reference, it is essential to note that MySQL does not allow modifying the same table from a subquery within the same query. To circumvent this restriction, the query can be split into two separate queries: a SELECT query to identify the rows to be deleted, followed by a DELETE query to execute the deletion. Alternatively, a nested subquery with an alias can be used to allow for the deletion within a single query.

The above is the detailed content of How to Efficiently Delete Non-Unique Rows in MySQL 5.0?. 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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template