唯一键(unique key)
唯一键:unique key,用来保证对应的字段中的数据唯一的
主键也可以用来保证字段数据唯一性,但是一张表只有一个主键。
1、唯一键在一张表中可以有多个
2、唯一键允许字段数据为NULL,NULL可以有多个(NULL不参与比较)
创建唯一键
创建唯一键与创建主键非常类似
1、直接在表字段之后增加唯一键标识符:unique[key]
2、在所有的字段之后使用unique key(字段列表)
3、在创建完表之后也可以增加唯一键
alter table 表名 add unique key(字段列表)
mysql> create table unique1(
-> id int primary key auto_increment,
-> username varchar(10) unique
-> )charset utf8;
Query OK, 0 rows affected (1.75 sec)
mysql> create table unique2(
-> id int primary key auto_increment,
-> username varchar(10),
-> unique key(username)
-> )charset utf8;
Query OK, 0 rows affected (1.87 sec)
mysql> create table unique3(
-> id int primary key auto_increment,
-> username varchar(10)
-> )charset utf8;
Query OK, 0 rows affected (1.82 sec)
-- mys