如何确保MySQL行是唯一的?
要确保MySQL行是唯一的,需要使用唯一约束。让我们先创建一个表−
mysql> create table DemoTable1580 -> ( -> id int, -> Name varchar(20), -> Age int -> ); Query OK, 0 rows affected (0.73 sec)
这里有一个查询,它创建唯一约束以确保MySQL行是唯一的−
mysql> alter table DemoTable1580 add unique index(id,Name,Age); Query OK, 0 rows affected (0.45 sec) Records: 0 Duplicates: 0 Warnings: 0
使用插入命令在表中插入一些记录−
mysql> insert into DemoTable1580 values(101,'Chris',21); Query OK, 1 row affected (0.24 sec) mysql> insert into DemoTable1580 values(102,'Chris',21); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable1580 values(102,'David',21); Query OK, 1 row affected (0.49 sec) mysql> insert into DemoTable1580 values(101,'Chris',21); ERROR 1062 (23000): Duplicate entry '101-Chris-21' for key 'id'
使用选择语句从表中显示所有记录−
mysql> select * from DemoTable1580;
这将产生以下输出−
+------+-------+------+ | id | Name | Age | +------+-------+------+ | 101 | Chris | 21 | | 102 | Chris | 21 | | 102 | David | 21 | +------+-------+------+ 3 rows in set (0.00 sec)
广告