MySQL数据库中表的 <约束>

概念:对表中的数据进行限定,保证数据的正确性、有效性和完整性。

分类:

  1. 主键约束:primary key
  2. 非空约束:not null
  3. 唯一约束:unique
  4. 自动增长:auto_increment
  5. 外键约束:foreign key

下面一个一个的介绍每一种约束:

1、非空约束:not null ,某一列的值不能为null

添加非空约束:

1.1 创建表时添加非空约束:

create table stu(
    id int,
    name varchar(20) not null --name为非空
);

1.2 创建表之后,添加非空约束:

alter table stu modify name varchar(20) not null;

1.3 删除name的非空约束:

alter table stu modify name varchar(20);

2、唯一约束: unique ,某一列的值不能重复(可以有null值,但只能有一条记录为null)

2.1 创建表时添加唯一约束:

create table stu(
    id int,
    phone_number varchar(20) unique --手机号唯一
);

2.2 创建表之后,添加唯一约束: 

alter table stu modify phone_number varchar(20) unique;

2.3 删除phone_number的唯一约束:

alter table stu drop index phone_number;

3、主键约束:primary key ,某一列的值非空且唯一,一张表只能有一个字段为主键,主键就是表中记录的唯一标识

3.1 创建表时添加主键约束:

create table stu(
    id int primary key, --给id添加主键约束
    name varchar(20)
);

3.2 创建表之后,添加主键约束:

alter table stu modify id int primary key;

3.3 删除id的主键约束:

alter table stu drop primary key;

4、自动增长:如果某一列是数值类型的,使用 auto_increment 可以来完成值的自动增长

4.1 创建表时添加主键约束,并且完成主键的自动增长:

create table stu(
    id int primary key auto_increment, --给id添加主键约束,并自动增长
    name varchar(20)
);

4.2 添加数据:会自动根据上一条数据的id加1赋值给当前数据的id

insert into stu values(null,'aaa');

4.3 创建表之后,添加主键约束,并且完成主键的自动增长:

alter table stu modify id int auto_increment;

4.4 删除主键的自动增长:

alter table stu modify id int;

5、 外键约束:foreign key ,让表与表产生关系,从而保证数据的正确性。

5.1 语法:

create table 表名(
    ...
    外键列
    constraint 外键名称 foreign key (外键列名称) references 被关联表名称(被关联表列名称)
);

5.2 创建表时添加外键约束:

create table department(--创建部门表
    id int primary key auto_increment,--部门编号,主键,自动增长
    dep_name varchar(20),--部门名称
    dep_location varchar(20),--部门地址
);

create table employee(--创建员工表
    id int primary key auto_increment,--员工编号,主键,自动增长
    name varchar(20),--员工姓名
    age int,--员工年龄
    dep_id int,--外键对应主表的主键
    constraint emp_dept_fk foreign key (dep_id) references department(id)
    --emp_dept_fk是外键名称,dep_id是外键列名称,department(id)是被关联表名称(被关联表列名称)
);

 5.3 创建表之后,添加外键约束:

alter table employee add constraint emp_dept_fk foreign key (dep_id) references department(id);

5.4 删除外键:

alter table employee drop foreign key emp_dept_fk;

6、级联操作(使用时要慎用)

 6.1 在5.3的基础上设置级联更新:

alter table employee add constraint emp_dept_fk foreign key (dep_id) references department(id) on update cascade;

6.2 在6.1的基础上也可以接着设置级联删除: 

alter table employee add constraint emp_dept_fk foreign key (dep_id) references department(id) on update cascade on detele cascade;
 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值