简体   繁体   English

删除SQL重复项

[英]Remove SQL duplicates

I'm totally new in SQL. 我对SQL完全陌生。 I never used it and just need a simple answer because I don't have time to learn SQL right now :(. I need to remove duplicated records from my local DB. Case looks like this: 我从没使用过它,只需要一个简单的答案,因为我现在没有时间学习SQL :(。我需要从本地数据库中删除重复的记录。

 | id | type | ... | ------------------- | 1 | test | ... | | 1 | test2 | ... | | 1 | test | ... | | 1 | test | ... | 
I want to remove all duplicated record which has the same id and type but leave only on record. 我想删除所有具有相同idtype重复记录,但只保留记录。 Like this: 像这样:

 | id | type | ... | ------------------- | 1 | test | ... | | 1 | test2 | ... | 

Using delete by Id is impossible. 无法使用按ID删除。 I have 50k records and I want to remove all duplicated records. 我有5万条记录,我想删除所有重复的记录。 When ID and Type are the same. 当ID和类型相同时。

Please try this 请尝试这个

First Way 第一路

 SELECT id, type
        FROM table_name
  Group by id, type

Second Way 第二路

 SELECT DISTINCT id, type
        FROM table_name;

SELECT DISTINCT statement is used to return only distinct (different) values. SELECT DISTINCT语句仅用于返回不同的(不同的)值。

Inside a table, a column often contains many duplicate values; 在表内部,一列通常包含许多重复值; and sometimes you only want to list the different (distinct) values. 有时您只想列出不同的(不同的)值。

SELECT DISTINCT column1, column2, ...
FROM table_name;

In your table 在你的桌子上

 SELECT DISTINCT id, type, ...
    FROM table_name;

您只需要在选择伴侣时使用关键字distinct即可。

 SELECT DISTINCT id, type, blah blah blah FROM your_table; // this should take care of em

A TSQL sample code that might help: TSQL示例代码可能会有所帮助:

 WITH tbl_alias AS
    (
       SELECT id, type,
           RN = ROW_NUMBER()OVER(PARTITION BY id, type ORDER BY id)
       FROM tbl
    )
    DELETE FROM tbl_alias WHERE RN > 1

Also you can try How to delete duplicates on a MySQL table? 您也可以尝试如何删除MySQL表上的重复项? .

You should replace your table grouping by id and type, and using an aggregate function on the other fields. 您应该用ID和类型替换表分组,并在其他字段上使用聚合函数。

You should add to your question the definition of your table and specify the rule to use to get the other fields. 您应该在问题中添加表的定义,并指定用于获取其他字段的规则。 Anyway, this is a simple solution: 无论如何,这是一个简单的解决方案:

-- Create a temp copy of original table with distinct values
CREATE TEMPORARY TABLE copy_table1 
   SELECT id, type, MIN(field3) AS field3, ...
   FROM table1
   GROUP BY id, type;

-- Empty original table
DELETE FROM table1;

-- Insert distinct data into original table
INSERT INTO table1 (id, type, field3, ...) 
    SELECT id, type, field3, ...
    FROM copy_table1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM