mysql 唯一約束 Mysql 唯一性約束新增

2021-10-25 14:16:38 字數 2061 閱讀 6539

一、單列唯一約束

1.建表時加上唯一性約束:

create table `t_user` (

`id` int(11) not null auto_increment,

`username` varchar(18) not null unique,

`password` varchar(18) not null,

primary key (`id`)

) engine=innodb auto_increment=1018 default charset=gbk;

2.給已經建好的表加上唯一性約束:

alter table `t_user` add unique(`username`);

或者:create unique index usernameindex on 't_user' ('username');

二、多列聯合唯一約束

1.確認表結構

mysql> show create table jw_resource;

field type collation null key default extra privileges comment

id bigint(20) (null) no pri (null) auto_increment select,insert,update

resource_name varchar(128) gbk_chinese_ci yes (null) select,insert,update

resource_type tinyint(4) (null) yes (null) select,insert,update

2.給resource_name和resource_type新增聯合唯一約束:

mysql> show index from jw_resource;

mysql> alter table jw_resource

add unique key(resource_name, resource_type);

3.確認表結構新增約束後結果:

mysql> show create table jw_resource;

create table `jw_resource` (

`id` bigint(20) not null auto_increment,

`resource_name` varchar(128) default null,

`resource_type` tinyint(4) default null,

primary key (`id`),

unique key `resource_name` (`resource_name`,`resource_type`)

) engine=innodb auto_increment=2 default charset=gbk;

mysql> show index from jw_resource;

注意:唯一鍵約束新增後,在建表的元資料中,預設的唯一鍵約束名稱為第一列的名稱。

4.新增約束後,進行插入測試效果:

msyql> insert into `jw_resource`(`resource_name`,'resource_type') values('aa','11');

msyql> insert into `jw_resource`(`resource_name`,'resource_type') values('aa','22');

msyql> insert into `jw_resource`(`resource_name`,'resource_type') values('bb','11');

msyql> insert into `jw_resource`(`resource_name`,'resource_type') values('aa','11');

5.刪除唯一約束

mysql> alter table jw_resource drop index `resource_name`;

mysql> show index from jw_resource;

注意:唯一鍵約束新增後,實際上建立了乙個索引,將該索引刪除後,就等於刪除了聯合唯一約束。

MySQL 新增唯一約束和聯合唯一約束

在mysql資料庫中,經常會碰到由於業務需要新增唯一鍵約束,唯一鍵約束,可以在乙個列上新增約束,也可以在多個列上新增唯一約束。1.建表時加上唯一性約束 create table t user id int 11 notnull auto increment username varchar 18 n...

mysql唯一約束指令 mysql使用總結

1,mysql唯一性約束 用alter命令,如下 表名為user,欄位為name alter table user add unique key name 2,mysql中刪除乙個表中的某字段的unique key的語法 alter table table123212 drop index name...

MySQL唯一約束,主鍵,外來鍵

唯一約束 新增方法 id int unique alter table customers add constraint uq unique id 刪除方法 alter table customers drop index uq 主鍵作用 primary key unique not null 新增...