Create table A (id int) 注意:id列非自增,由代码产生并输入,但代码可能产生重复id
1.业务定义中,id列不允许重复,用什么方式保证重复的id不会被输入表中?
2.若已经发生数据重复,请写出SQL语句,找出重复数据,删除重复
以下面为例子:
create table b(id int);
insert into b values(1),(2),(2),(2),(2),(2),(3),(3),(2),(4);
-- 查询重复
select id,count(*) from b group by id having count(*)>1;
查询重复结果:
完全重复:
-- 全重
create table b2 like b;
insert into b2 select distinct * from b;
truncate b;
insert into b select * from b2;
drop table b2;
show tables ;
select * from b;
局部重复并删除重复:
create table c(
id int unsigned auto_increment primary key ,
name varchar(50),
age tinyint unsigned default 18
);
insert into c values (null,'李四',20),(null,'王五',20),(null,'李四',30),(null,'张三',20),(null,'张三',20),(null,'张三',20);
select * from c;
select name,count(*) from c group by name;
-- 删除姓名重复的
delete from c where id not in (select * from (select max(id) from c group by name) as t);
-- 删除姓名和年龄
delete from c where id not in(
select max(id) from (select id,concat(name,age) info from c) t1 group by info);