场景:
爬取的数据生成数据表,结构与另一个主表相同,需要进行合并+去重
解决:(直接举例)
首先创建两个表pep,pep2,其中pep是主表
CREATE TABLE IF NOT EXISTS `pep/pep2`( `id` INT UNSIGNED AUTO_INCREMENT, `no` VARCHAR(100) NOT NULL, PRIMARY KEY ( `id` ) )ENGINE=InnoDB DEFAULT CHARSET=utf8;
然后向pep中插入两条数据,pep2中插入一条与pep中相同的一条数据
insert into pep(no) values('abc'); insert into pep(no) values('caa'); insert into pep2(no) values('abc');
将pep2的数据插入pep中
insert into pep (no) select no from pep2;
分组去重创建新的临时表tmp
create table tmp select id,no from pep group by no;
注意:创建完这个表的id字段类型已经不是主键自增
可能也会报错 ```Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'XXX.Y.ZZZZ' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by ``` 解决:执行以下两个命令: ``` mysql> set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'; mysql> set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'; ```
删除pep表,并将tmp表重命名为pep
drop table pep; alter table tmp rename to pep;
查看desc结构和select * from pep发现id的字段类型变了,这里需要改回原来的类型;
alter table pep add primary key (id); alter table pep modify id int auto_increment;