时间:2021-07-01 10:21:17 帮助过:10人阅读
在这里,我们设定一个表,其结构如下:
mysql> desc `user`;
+-------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | char(10) | NO | | | |
| extra | char(10) | NO | | | |
+-------+------------------+------+-----+---------+----------------+
原来表中的数据假定有以下几条:
mysql> SELECT * FROM `user`;
+----+-------+--------+
| id | name | extra |
+----+-------+--------+
| 1 | user1 | user1 |
| 2 | user2 | user2 |
| 3 | user3 | user3 |
| 4 | user4 | user4 |
| 5 | user5 | user5 |
| 6 | user3 | user6 |
| 7 | user6 | user7 |
| 8 | user2 | user8 |
| 9 | USER2 | user9 |
| 10 | USER6 | user10 |
+----+-------+--------+
1、将原来的数据导出
mysql>SELECT * INTO OUTFILE '/tmp/user.txt' FROM `user`;
2、清空数据表
mysql>TRUNCATE TABLE `user`;
3、创建唯一索引,并且修改 `name` 字段的类型为 BINARY CHAR 区分大小写
mysql> ALTER TABLE `user` MODIFY `name` CHAR(10) BINARY NOT NULL DEFAULT '';
mysql> ALTER TABLE `user` ADD UNIQUE KEY ( `name` );
现在来看看新的表结构:
mysql> desc user;
+-------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | char(10) | NO | UNI | | |
| extra | char(10) | NO | | | |
+-------+------------------+------+-----+---------+----------------+
4、把数据导回去,在这里,有两种选择:新的重复记录替换旧的记录,只保留最新的记录 或者是 新的记录略过,只保留最旧的记录
mysql> LOAD DATA INFILE '/tmp/user.txt' REPLACE INTO TABLE `user`;
Query OK, 10 rows affected (0.00 sec)
Records: 8 Deleted: 2 Skipped: 0 Warnings: 0
mysql> SELECT * FROM USER;
+----+-------+--------+
| id | name | extra |
+----+-------+--------+
| 1 | user1 | user1 |
| 8 | user2 | user8 |
| 6 | user3 | user6 |
| 4 | user4 | user4 |
| 5 | user5 | user5 |
| 7 | user6 | user7 |
| 9 | USER2 | user9 |
| 10 | USER6 | user10 |
+----+-------+--------+
上面是采用 REPLACE 的方式,可以看到,导入过程中删掉了两条数据,结果验证确实是 新的重复记录替换旧的记录,只保留最新的记录。
现在,来看看用 IGNORE 的方式:
mysql> LOAD DATA INFILE '/tmp/user.txt' IGNORE INTO TABLE `user`;
Query OK, 6 rows affected (0.01 sec)
Records: 8 Deleted: 0 Skipped: 2 Warnings: 0
mysql> SELECT * FROM USER;
+----+-------+--------+
| id | name | extra |
+----+-------+--------+
| 1 | user1 | user1 |
| 2 | user2 | user2 |
| 3 | user3 | user3 |
| 4 | user4 | user4 |
| 5 | user5 | user5 |
| 7 | user6 | user7 |
| 9 | USER2 | user9 |
| 10 | USER6 | user10 |
+----+-------+--------+
看到了吧,确实是 新的记录略过,只保留最旧的记录。