MySQL基础-约束

本文介绍了MySQL中常见的约束类型,包括自动增长(auto_increment)、非空(notnull)和唯一(unique)约束,并展示了如何在创建和修改表时应用这些约束。此外,还讲解了外键约束在外键管理中的作用,以及如何添加、删除外键,以及设置删除和更新时的联动行为。强调了外键对于数据一致性和完整性的保障。
摘要由CSDN通过智能技术生成

MySQL基础-约束

注意:约束时作用于表中的字段上的,可以在创建表或者修改表的时候添加约束

约束

  • auto_increment 自动增长
  • not null 非空约束
  • unique 唯一约束
create table user(
    id int primary key auto_increment comment '主键',
    name varchar(10) not null unique comment '姓名
    /*
    因为MySql不是8.0.16之后的版本,无法使用检查约束
    */
    age int comment '年龄',
    status char(1) default '1' comment '状态',
    gender char(1) comment '性别'
)comment '用户表';
-- 主键约束 primary key(自增 AUTO_INCREMENT)
insert into user(name, age, status, gender) values ('Tom1','19','1','男'),('Tom2','25','0','男');
-- 非空约束 not null
insert into user(name, age, status, gender) values (null,'19','1','男');
-- 唯一约束 unique
insert into user(name, age, status, gender) values ('Tom1','19','1','男');
-- 检查约束 check() MySql 8.0.16之后可用

外键约束

注意:数据库中的两张表,如未在数据库层面建立外键链接,是无法保证数据的一致性和完整性的。

-- 添加外键
alter table employees add constraint fk_employees_dept_id foreign key (dept_id) references dept(id);
-- 删除外键
alter table employees drop foreign key fk_employees_dept_id;

删除/更新行为

-- 删除或者更新时绑定更新操作
alter table employees add constraint fk_employees_dept_id foreign key (dept_id) references dept(id) on update cascade on delete cascade ;
-- 删除或者更新时绑定设null操作
alter table employees add constraint fk_employees_dept_id foreign key (dept_id) references dept(id) on UPDATE set null on DELETE set null ;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BXuan随笔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值