Mysql 专题
专题目录
您的位置:database > Mysql专题 > MySQL 处理重复数据
MySQL 处理重复数据
作者:--    发布时间:2019-11-20

有些 mysql 数据表中可能存在重复的记录,有些情况我们允许重复数据的存在,但有时候我们也需要删除这些重复的数据。

本章节我们将为大家介绍如何防止数据表出现重复数据及如何删除数据表中的重复数据。


防止表中出现重复数据

你可以在mysql数据表中设置指定的字段为 primary key(主键) 或者 unique(唯一) 索引来保证数据的唯一性。

让我们尝试一个实例:下表中无索引及主键,所以该表允许出现多条重复记录。

create table person_tbl
(
    first_name char(20),
    last_name char(20),
    sex char(10)
);

如果你想设置表中字段first_name,last_name数据不能重复,你可以设置双主键模式来设置数据的唯一性, 如果你设置了双主键,那么那个键的默认值不能为null,可设置为not null。如下所示:

create table person_tbl
(
   first_name char(20) not null,
   last_name char(20) not null,
   sex char(10),
   primary key (last_name, first_name)
);

如果我们设置了唯一索引,那么在插入重复数据时,sql语句将无法执行成功,并抛出错。

insert ignore into与insert into的区别就是insert ignore会忽略数据库中已经存在的数据,如果数据库没有数据,就插入新的数据,如果有数据的话就跳过这条数据。这样就可以保留数据库中已经存在数据,达到在间隙中插入数据的目的。

以下实例使用了insert ignore into,执行后不会出错,也不会向数据表中插入重复数据:

mysql> insert ignore into person_tbl (last_name, first_name)
    -> values( 'jay', 'thomas');
query ok, 1 row affected (0.00 sec)
mysql> insert ignore into person_tbl (last_name, first_name)
    -> values( 'jay', 'thomas');
query ok, 0 rows affected (0.00 sec)

insert ignore into当插入数据时,在设置了记录的唯一性后,如果插入重复数据,将不返回错误,只以警告形式返回。 而replace into如果存在primary 或 unique相同的记录,则先删除掉。再插入新记录。

另一种设置数据的唯一性方法是添加一个unique索引,如下所示:

create table person_tbl
(
   first_name char(20) not null,
   last_name char(20) not null,
   sex char(10)
   unique (last_name, first_name)
);

查询重复记录

select user_name,count(*) as count from user_table group by user_name having count>1;
select * from people 
where peopleid in (select peopleid from people group by peopleid having count(peopleid) > 1) 

统计重复数据

以下我们将统计表中 first_name 和 last_name的重复记录数:

mysql> select count(*) as repetitions, last_name, first_name
    -> from person_tbl
    -> group by last_name, first_name
    -> having repetitions > 1;

以上查询语句将返回 person_tbl 表中重复的记录数。 一般情况下,查询重复的值,请执行以下操作:

  • 确定哪一列包含的值可能会重复。
  • 在列选择列表使用count(*)列出的那些列。
  • 在group by子句中列出的列。
  • having子句设置重复数大于1。

过滤重复数据

如果你需要读取不重复的数据可以在 select 语句中使用 distinct 关键字来过滤重复数据。

mysql> select distinct last_name, first_name
    -> from person_tbl
    -> order by last_name;

你也可以使用 group by 来读取数据表中不重复的数据:

mysql> select last_name, first_name
    -> from person_tbl
    -> group by (last_name, first_name);

删除重复数据

如果你想删除数据表中的重复数据,你可以使用以下的sql语句:

mysql> create table tmp select last_name, first_name, sex
    ->                  from person_tbl;
    ->                  group by (last_name, first_name);
mysql> drop table person_tbl;
mysql> alter table tmp rename to person_tbl;

当然你也可以在数据表中添加 index(索引) 和 primay key(主键)这种简单的方法来删除表中的重复记录。方法如下:

mysql> alter ignore table person_tbl
    -> add primary key (last_name, first_name);
网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册