MySQL基础之约束

MySQL基础之约束

概述

  • 概念:约束是作用在字段的规则,限制表中数据

演示

mysql 复制代码
# 多个约束之间不需要加逗号
# auto_increment 自增
create table user(
    id int primary key auto_increment comment '主键',
		name varchar(10) not null unique comment '姓名',
		age int check( age > 0 && age <= 120 ) comment '年龄',
		status char(1) default '1' comment '状态',
		gender char(1) comment '性别'
) comment '用户表';

外键约束

  • 概念:让两张表的数据建立连接
mysql 复制代码
# 创建表时添加外键
create table 表名(
	字段名 数据类型,
    ...
    [constraint] [外键名称] foreign key(外键字段名) references 主表(主表列名)
)
# 创建表后添加外键
alter table 表名 add constraint 外键名称 foreign key(外键字段名) references 主表(主表列名);
# 删除外键
alter table 表名 drop foreign key 外键名称;
mysql 复制代码
# 示例
# 把dept表中主键id 与cmp表中dept_id连接 建立外键fk_cmp_id_dept
alter table cmp add CONSTRAINT fk_cmp_id_dept FOREIGN key (dept_id) REFERENCES dept(id);
# 把fk_cmp_id_dept外键删除
alter table cmp drop foreign key fk_cmp_id_dept;

删除/更新行为

  • 添加外键时在末尾加上即可
mysql 复制代码
# 在更新或删除主表中的数据时会级联副表中数据
alter table cmp add CONSTRAINT fk_cmp_id_dept FOREIGN key (dept_id) REFERENCES dept(id) on update cascade on delete cascade; 

# 在删除主表中的数据时会使副表中数据置null
alter table cmp add CONSTRAINT fk_cmp_id_dept FOREIGN key (dept_id) REFERENCES dept(id) on delete set null; 
相关推荐
程序员码歌38 分钟前
【零代码AI编程实战】AI灯塔导航-总结篇
android·前端·后端
书弋江山2 小时前
flutter 跨平台编码库 protobuf 工具使用
android·flutter
听雪楼主.2 小时前
Oracle Undo Tablespace 使用率暴涨案例分析
数据库·oracle·架构
我科绝伦(Huanhuan Zhou)2 小时前
KINGBASE集群日常维护管理命令总结
数据库·database
妖灵翎幺2 小时前
Java应届生求职八股(2)---Mysql篇
数据库·mysql
HMBBLOVEPDX2 小时前
MySQL的事务日志:
数据库·mysql
来来走走4 小时前
Flutter开发 webview_flutter的基本使用
android·flutter
weixin_419658315 小时前
MySQL数据库备份与恢复
数据库·mysql
wml000005 小时前
CentOS启动两个MySQL实例
mysql·centos·3406
Jerry说前后端5 小时前
Android 组件封装实践:从解耦到架构演进
android·前端·架构