要在不存在记录时插入,请将列设置为UNIQUE INDEX。让我们首先创建一个表-
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(20) );
以下是创建唯一索引以插入'FirstName'列中不存在的记录的查询-
mysql> CREATE UNIQUE INDEX index_on_FirstName ON DemoTable(FirstName); Records: 0 Duplicates: 0 Warnings: 0
使用insert命令在表中插入一些记录。现在在这里您可以检查insert命令仅插入那些不存在的记录-
mysql> insert into DemoTable(FirstName) values('Chris'); mysql> insert into DemoTable(FirstName) values('Chris'); ERROR 1062 (23000): Duplicate entry 'Chris' for key 'index_on_FirstName' mysql> mysql> insert into DemoTable(FirstName) values('Robert'); mysql> insert into DemoTable(FirstName) values('Mike'); mysql> insert into DemoTable(FirstName) values('Robert'); ERROR 1062 (23000): Duplicate entry 'Robert' for key 'index_on_FirstName' mysql>
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+----+-----------+ | Id | FirstName | +----+-----------+ | 1 | Chris | | 2 | Robert | | 3 | Mike | +----+-----------+ 3 rows in set (0.00 sec)