Home  >  Article  >  Database  >  MySQL中的唯一索引的简单学习教程_MySQL

MySQL中的唯一索引的简单学习教程_MySQL

PHP中文网
PHP中文网Original
2016-05-27 13:45:361940browse

mysql 唯一索引UNIQUE一般用于不重复数据字段了我们经常会在数据表中的id设置为唯一索引UNIQUE,下面我来介绍如何在mysql中使用唯一索引UNIQUE吧。
创建唯一索引的目的不是为了提高访问速度,而只是为了避免数据出现重复。唯一索引可以有多个但索引列的值必须唯一,索引列的值允许有空值。如果能确定某个数据列将只包含彼此各不相同的值,在为这个数据列创建索引的时候就应该使用关键字UNIQUE。

把它定义为一个唯一索引。


创建表时直接设置:


DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`stu_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`stu_id`),
UNIQUE KEY `UK_student_name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;


创建唯一索引:


create unique index UK_student_name on student (name);


建表后添加约束:


alter table student add constraint uk_student_name unique (name);


如果不需要唯一索引,则可以这样删除


mysql> ALTER TABLE student DROP INDEX name;



Query OK, 0 rows affected (0.85 sec)



如果要增加索引

alter table user add unique index(user_id,user_name);


 以上就是MySQL中的唯一索引的简单学习教程_MySQL的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn