MySQL中四种约束简述。

版权声明:本文为博主原创文章,未经允许不得转载 https://blog.csdn.net/qq_38545819/article/details/85933061

一.数据的完整性

  1. 域完整性
  2. 实体完整性
  3. 引用完整性

二.约束

1. 非空约束 not null
insert into teacher(id,sex,birthday)
values(1,'male','2018-5-5')

会报错,因为name项有非空约束

取消非空约束:
alter table teacher modify name vachar(10);

如果要继续为name加上非空约束,应该先删掉name的值,然后再执行以下语句,否则会报错。
alter table teacher  modify name varchar(10) not null;

或者:

alter table teacher change name name varchar (10) not null;
2. 唯一约束 unique
create table test_unique(
    id int(10),
    name varchar(32) not null,
    email varchar(128) unique
);
添加数据
insert into test_unique values(1,'zmt','[email protected]')
取消唯一性约束:

语法:alter table 表名 drop index 字段名;

alter table test_unique drop index email;
建表后添加唯⼀性约束:

语法:alter table 表名 add unique(字段名)

alter table test_unique add unique(id);
3.主键约束
create table test3_primary(
    id int not null,
    name varchar(50) not null,
    primary key(id,name)
);
insert into test3_primary values(1,'abc')
删除主键约束:

语法:alter table 表名 drop primary key;

alter table test3_primary drop primary key;
建表后添加主键约束:

语法:alter table 表名 add primary key(字段名)

alter table test3_primary add primary key(id) ; --将字段设置为主键
4. 默认值约束 default
create table test1_default(
    id int not null,
    name varchar(50) not null DEFAULT 'abc'
);

插⼊数据的时候,如果不写⼊name的值,则默认显示填入abc

删除默认值约束:

语法:alter table 表名 change 字段 字段 字段类型 not null

alter table test1_default change name name varchar(50) not null
建表后添加默认值约束:

语法:alter table 表名 modify 列名 列类型 not null default ‘默认值’;

alter table test1_default modify name varchar(50) not null default 'abc';
5.外键约束
建表的同时建外键
create table emp(
	.......
	foreign key(外键字段) references dept(deptno)
)
建立表之后添加外键
alter table emp add foreign key(deptno) references dept(deptno)
删除外键:
语法:alter table 表名称 drop foreign key 外键名称;
例:alter table empA drop foreign key empa_ibQk_1;
注意:如果没有在建表的时候标明外键名称,可以通过:
show create table 表名 进⾏查看外键名称;

猜你喜欢

转载自blog.csdn.net/qq_38545819/article/details/85933061