MySQL之DDL增强(添加约束)

约束分类:主键,primary;外键,foreign key; 唯一, unique;非空,not null;自增,auto_increment;默认值,default

实体完整性(主键)
主键设置可以划分为两种
第一种 : 创建表语句时,添加主键约束
create table person(
id int ,
name varchar(100),
income decimal(18,2),
primary key (id,name)
);
上面代码设置了两个主键
create table person1(
id int ,
name varchar(100),
income decimal(18,2),
primary key (id)
);
上面代码设置了一个主键
如果只有一列主键,也可以直接写在字段后面
create table person2(
id int primary key,
name varchar(100) ,
income decimal(18,2)
);
第二种 : 创建表完成之后,通过alter添加主键约束
语法 : alter table 表名 add primary key(列名,列名…);
create table person3(
id int ,
name varchar(100),
income decimal(18,2)
);
比如要对person3表添加id列主键
alter table person3 add primary key(id);
主键自增
第一种 : 建表时,添加自增
create table person4(
id int auto_increment ,
name varchar(200),
primary key(id)
);
测试语句 :
insert into person4(name)values(‘测试’);
并未输入id的值,但是可以自动填充
第二种 : 创建表之后,添加自增
语法 : alter table 表名modify 主键列名 类型 auto_increment;
create table person5(
id int ,
name varchar(200),
primary key(id)
);
alter table person5 modify id int auto_increment;
测试语句 :
insert into person5 (name)values(‘测试’);
并未输入id的值,但是可以自动填充
设置自增的起始值
语法 : alter table 表名auto_increment=值;
create table person6(
id int auto_increment ,
name varchar(200),
primary key(id)
);
alter table person6 auto_increment=10000;
测试语句 :
insert into person6 (name)values(‘测试’);
Id值从10000开始
关联完整性(外键)
第一种 : 创建表时添加外键约束
create table teacher(
id int ,
name varchar(20),
primary key (id)
);
create table student (
id int ,
name varchar(20),
teacher_id int ,
primary key (id),
foreign key (teacher_id) references teacher(id)
第二种 : 创建完表之后,添加外键约束
create table student1 (
id int ,
name varchar(20),
teacher_id int,
primary key (id)
);
create table teacher1(
id int ,
name varchar(20),
primary key (id)
);
语法 : alter table 表名 add foreign key (外键列列名) references 指向的表名 (主键列列名);
alter table student1 add foreign key (teacher_id) references teacher1 (id);
唯一约束unique
第一种 : 创建表时,添加unique约束
create table temp (
id int ,
name varchar(20),
unique(id)
);

create table temp (
id int unique ,
name varchar(20)
);
第二种 : 创建表之后,添加unique约束
create table temp1 (
id int ,
name varchar(20)
);
alter table temp1 add unique (id);
非空约束 not null与 默认值 default
第一种 : 创建表时,添加约束
create table temp2(
id int not null,
name varchar(30) default ‘abc’,
sex varchar(10) not null default ‘男’
);
第二种 : 创建表之后,添加约束
语法 : alter table 表名 modify 列名 数据类型 not null default 默认值;

create table temp3(
id int,
name varchar(30) ,
sex varchar(10)
);
alter table temp3 modify id int not null ;
alter table temp3 modify name varchar(30) default ‘abc’;
alter table temp3 modify sex varchar(10) not null default ‘男’;
Check扩展约束
CHECK:检查约束(MySql不支持),检查字段的值是否为指定的值
一般用于性别等,对列的值做一些限制,比如 性别列的值只能是男或者女
但是MySQL这里给舍弃了,不再支持,所以六大约束就成了五大约束

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值