如果确定某个数据列只包含彼此各不相同的值,在为这个数据列创建索引的时候,就应该用关键字unique把它定义为一个唯一索引。
mysql会在有新纪录插入数据表时,自动检查新纪录的这个字段的值是否已经在某个记录的这个字段里出现过了。如果是,mysql将拒绝插入那条新纪录。
也就是说,唯一索引可以保证数据记录的唯一性。事实上,在许多场合,人们创建唯一索引的目的往往不是为了提高访问速度,而只是为了避免数据出现重复。
创建唯一索的方法
操作表
create table `wb_blog` ( `id` smallint(8) unsigned not null, `catid` smallint(5) unsigned not null default '0', `title` varchar(80) not null default '', `content` text not null, primary key (`id`), )
创建唯一索可以使用关键字unique随表一同创建
注:这是在命令行窗口进行操作mysql> create table `wb_blog` ( -> `id` smallint(8) unsigned not null, -> `catid` smallint(5) unsigned not null default '0', -> `title` varchar(80) not null default '', -> `content` text not null, -> primary key (`id`), -> unique key `catename` (`catid`) -> ) ; query ok, 0 rows affected (0.24 sec)
上面代码为wb_blog表的'catid'字段创建名为catename的唯一索引
2、在创建表之后使用create命令来创建
mysql> create unique index catename on wb_blog(catid); query ok, 0 rows affected (0.47 sec)
如果不需要唯一索引,则可以这样删除
mysql> alter table wb_blog drop index catename; query ok, 0 rows affected (0.85 sec)
以上就是mysql唯一索引什么意思的详细内容。