search
HomeDatabaseMysql Tutorialmysql中删除重复记录sql语句

在sql中我们经常会碰到有重复的一些数据,下面我来介绍在mysql中删除重复记录的多种方法,有需要的朋友可参考参考。

删除重复记录方法一:

1. 新建一个临时表

 代码如下 复制代码

create table tmp as select * from youtable group by  name(name为不希望有重复的列)

2. 删除原来的表

 代码如下 复制代码

drop table youtable

3. 重命名表

 代码如下 复制代码

alter table tmp rename youtable

但是这个方法有个问题,由临时表转变过来的最终表,其表结构会和原来的不一致,需要手工更改。这个问题,待解决。
删除重复记录方法二:

1. 新建一个临时表

 代码如下 复制代码

CREATE TABLE tmp AS SELECT * FROM youtable GROUP BY name(name为不希望有重复的列)

2. 清空原来的表

 代码如下 复制代码

TRUNCATE TABLE youtable

3. 把临时表插入到youtable

 代码如下 复制代码

INSERT INTO tablename SELECT  * FROM temp

4. 删除临时表

 代码如下 复制代码

DROP TABLE  temp

删除重复记录方法三:

 代码如下 复制代码

delete table where ID not in(select min(ID) from table group by name(name:重复的字段))

删除重复记录方法四:


具体实现如下:

 代码如下 复制代码

Table         Create Table                                           
------------  --------------------------------------------------------
users_groups  CREATE TABLE `users_groups` (                          
                `id` int(10) unsigned NOT NULL AUTO_INCREMENT,       
                `uid` int(11) NOT NULL,                              
                `gid` int(11) NOT NULL,                              
                PRIMARY KEY (`id`)                                   
              ) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8 

users_groups.txt内容:

1,11,502
2,107,502
3,100,503
4,110,501
5,112,501
6,104,502
7,100,502
8,100,501
9,102,501
10,104,502
11,100,502
12,100,501
13,102,501
14,110,501

mysql> load data infile 'c:\users_groups.txt' into table users_groups fields
terminated by ',' lines terminated by 'n';
Query OK, 14 rows affected (0.05 sec)
Records: 14  Deleted: 0  Skipped: 0  Warnings: 0

mysql> select * from users_groups;

query result(14 records)

id uid gid
1 11 502
2 107 502
3 100 503
4 110 501
5 112 501
6 104 502
7 100 502
8 100 501
9 102 501
10 104 502
11 100 502
12 100 501
13 102 501
14 110 501
14 rows in set (0.00 sec)

根据一位兄弟的建议修改。

 代码如下 复制代码

mysql> create temporary table tmp_wrap select * from users_groups group by uid having count(1) >= 1;
Query OK, 7 rows affected (0.11 sec)
Records: 7  Duplicates: 0  Warnings: 0

mysql> truncate table users_groups;
Query OK, 14 rows affected (0.03 sec)

mysql> insert into users_groups select * from tmp_wrap;
Query OK, 7 rows affected (0.03 sec)
Records: 7  Duplicates: 0  Warnings: 0

mysql> select * from users_groups;

query result(7 records)
id uid gid
1 11 502
2 107 502
3 100 503
4 110 501
5 112 501
6 104 502
9 102 501


mysql> drop table tmp_wrap;
Query OK, 0 rows affected (0.05 sec)

2、还有一个很精简的办法。

查找重复的,并且除掉最小的那个。

 代码如下 复制代码

delete users_groups as a from users_groups as a,
(
select *,min(id) from users_groups group by uid having count(1) > 1
) as b
 where a.uid = b.uid and a.id > b.id;
(7 row(s)affected)
(0 ms taken)
 
query result(7 records)
id uid gid
1 11 502
2 107 502
3 100 503
4 110 501
5 112 501
6 104 502
9 102 501

3、现在来看一下这两个办法的效率。
运行一下以下SQL 语句

 代码如下 复制代码

create index f_uid on users_groups(uid);
explain select * from users_groups group by uid having count(1) > 1 union all
select * from users_groups group by uid having count(1) = 1;
explain select * from  users_groups as a,
(
select *,min(id) from users_groups group by uid having count(1) > 1
) as b
 where a.uid = b.uid and a.id > b.id;
query result(3 records)
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY users_groups index (NULL) f_uid 4 (NULL) 14  
2 UNION users_groups index (NULL) f_uid 4 (NULL) 14  
(NULL) UNION RESULT ALL (NULL) (NULL) (NULL) (NULL) (NULL)  

 
query result(3 records)
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY ALL (NULL) (NULL) (NULL) (NULL) 4  
1 PRIMARY a ref PRIMARY,f_uid f_uid 4 b.uid 1 Using where
2 DERIVED users_groups index (NULL) f_uid 4 (NULL) 14  

 
 


很明显的第二个比第一个扫描的函数要少。

当没有创建表或创建索引权限的时候

创建一个新表,然后将原表中不重复的数据插入新表:

 代码如下 复制代码

mysql> create table demo_new as select * from demo group by site;
Query OK, 3 rows affected (0.19 sec)
Records: 3  Duplicates: 0  Warnings: 0
 
mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| demo           |
| demo_new       |
+----------------+
2 rows in set (0.00 sec)
 
mysql> select * from demo order by id;
+----+------------------------+
| id | site                   |
+----+------------------------+
|  1 | http://www.hzhuti.com  |
|  2 | http://111cn.net        |
|  3 | http://www.111cn.net |
|  4 | http://www.hzhuti.com  |
|  5 | http://www.111cn.net |
+----+------------------------+
5 rows in set (0.00 sec)
 
mysql> select * from demo_new order by id;
+----+------------------------+
| id | site                   |
+----+------------------------+
|  1 | http://www.hzhuti.com  |
|  2 | http://111cn.net        |
|  3 | http://www.111cn.net |
+----+------------------------+
3 rows in set (0.00 sec)

然后将原表备份,将新表重命名为当前表:

 代码如下 复制代码

mysql> rename table demo to demo_old, demo_new to demo;
Query OK, 0 rows affected (0.04 sec)
 
mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| demo           |
| demo_old       |
+----------------+
2 rows in set (0.00 sec)
 
mysql> select * from demo order by id;
+----+------------------------+
| id | site                   |
+----+------------------------+
|  1 | http://www.hzhuti.com  |
|  2 | http://111cn.net        |
|  3 | http://www.111cn.net |
+----+------------------------+
3 rows in set (0.00 sec)

Statement
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
How to solve the problem of mysql cannot open shared libraryHow to solve the problem of mysql cannot open shared libraryMar 04, 2025 pm 04:01 PM

This article addresses MySQL's "unable to open shared library" error. The issue stems from MySQL's inability to locate necessary shared libraries (.so/.dll files). Solutions involve verifying library installation via the system's package m

Reduce the use of MySQL memory in DockerReduce the use of MySQL memory in DockerMar 04, 2025 pm 03:52 PM

This article explores optimizing MySQL memory usage in Docker. It discusses monitoring techniques (Docker stats, Performance Schema, external tools) and configuration strategies. These include Docker memory limits, swapping, and cgroups, alongside

How do you alter a table in MySQL using the ALTER TABLE statement?How do you alter a table in MySQL using the ALTER TABLE statement?Mar 19, 2025 pm 03:51 PM

The article discusses using MySQL's ALTER TABLE statement to modify tables, including adding/dropping columns, renaming tables/columns, and changing column data types.

Run MySQl in Linux (with/without podman container with phpmyadmin)Run MySQl in Linux (with/without podman container with phpmyadmin)Mar 04, 2025 pm 03:54 PM

This article compares installing MySQL on Linux directly versus using Podman containers, with/without phpMyAdmin. It details installation steps for each method, emphasizing Podman's advantages in isolation, portability, and reproducibility, but also

What is SQLite? Comprehensive overviewWhat is SQLite? Comprehensive overviewMar 04, 2025 pm 03:55 PM

This article provides a comprehensive overview of SQLite, a self-contained, serverless relational database. It details SQLite's advantages (simplicity, portability, ease of use) and disadvantages (concurrency limitations, scalability challenges). C

How do I configure SSL/TLS encryption for MySQL connections?How do I configure SSL/TLS encryption for MySQL connections?Mar 18, 2025 pm 12:01 PM

Article discusses configuring SSL/TLS encryption for MySQL, including certificate generation and verification. Main issue is using self-signed certificates' security implications.[Character count: 159]

Running multiple MySQL versions on MacOS: A step-by-step guideRunning multiple MySQL versions on MacOS: A step-by-step guideMar 04, 2025 pm 03:49 PM

This guide demonstrates installing and managing multiple MySQL versions on macOS using Homebrew. It emphasizes using Homebrew to isolate installations, preventing conflicts. The article details installation, starting/stopping services, and best pra

What are some popular MySQL GUI tools (e.g., MySQL Workbench, phpMyAdmin)?What are some popular MySQL GUI tools (e.g., MySQL Workbench, phpMyAdmin)?Mar 21, 2025 pm 06:28 PM

Article discusses popular MySQL GUI tools like MySQL Workbench and phpMyAdmin, comparing their features and suitability for beginners and advanced users.[159 characters]

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor