Home > Database > Mysql Tutorial > Explain how mysql deletes duplicate data

Explain how mysql deletes duplicate data

藏色散人
Release: 2022-01-23 09:17:30
forward
10577 people have browsed it

This article will introduce to you how to delete duplicate data in MySQL. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

SKU should correspond to the only weight data corresponding to the SKU_ID, which causes the same redundant data due to program errors. Only keep one and delete the others.

##idincrement sku_idsku_idIDweightWeight
Field Description
Assume table name:

weight

Query a list with duplicate data

SELECT sku_id,COUNT(id) FROM weight GROUP BY sku_id HAVING COUNT(sku_id) > 1
Copy after login

Query duplicates For each smallest id in the data

SELECT min(id) FROM weight   GROUP BY sku_id HAVING COUNT(sku_id) > 1
Copy after login

Query other data with the smallest id that removes duplicate data

SELECT id,sku_id FROM weight WHERE sku_id IN(
    SELECT sku_id FROM weight   GROUP BY sku_id HAVING COUNT(sku_id) > 1)AND id NOT IN(
    SELECT MIN(id) FROM weight   GROUP BY sku_id HAVING COUNT(sku_id) > 1)
Copy after login

Delete other data with the smallest id that removes duplicate data Data

DELETE FROM weight WHERE sku_id IN(
    SELECT sku_id FROM weight   GROUP BY sku_id HAVING COUNT(sku_id) > 1)AND id NOT IN(
    SELECT MIN(id) FROM weight   GROUP BY sku_id HAVING COUNT(sku_id) > 1)
Copy after login
The reason is: while deleting this table, this table is queried at the same time, and this table is queried and deleted at the same time, which can be understood as a deadlock. Mysql does not support this operation of deleting and querying the same table

错误代码: 1093You can't specify target table 'weight' for update in FROM clause
Copy after login
The solution is as follows: Query the data to be deleted as a third-party table, and then filter and delete it.

DELETE FROM `weight` WHERE sku_id IN(
    SELECT sku_id FROM (SELECT sku_id FROM `weight` GROUP BY sku_id HAVING COUNT(sku_id) > 1) table1)AND id NOT IN (
    SELECT id FROM (SELECT MIN(id) AS id FROM `weight` GROUP BY sku_id HAVING COUNT(sku_id) > 1) table2)
Copy after login
The update also operates on the same principle as above.

Recommended learning: "

mysql video tutorial"

The above is the detailed content of Explain how mysql deletes duplicate data. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:learnku.com
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