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; 
相关推荐
言之。2 小时前
Django原子请求
数据库·django·sqlite
ICT董老师2 小时前
kubernetes中operator与helm有什么区别?部署mysql集群是选择operator部署还是helm chart部署?
linux·运维·mysql·云原生·容器·kubernetes
Codeking__2 小时前
Redis初识——Redis的基本特性
数据库·redis·缓存
霖霖总总2 小时前
[小技巧29]Batched Key Access:MySQL JOIN 性能优化的关键技术
数据库·mysql·性能优化
FrameNotWork2 小时前
Android Camera HAL实现windows摄像头显示:从黑屏到彩色照片的完整攻坚
android
中环留念3 小时前
MySQL 索引全解析:索引类型、聚簇索引、回表与性能优化
sql·mysql·索引·图解
Gobysec3 小时前
Goby 漏洞安全通告|MindsDB /api/sql/query 未授权访问漏洞(CVE-2025-68472)
数据库·sql·安全
m0_748245923 小时前
SQLite 数据类型概述
java·数据库·sqlite
五阿哥永琪3 小时前
MySQL 回表查询 性能代价?如何避免?
数据库·mysql
DBA小马哥3 小时前
文档型数据库MongoDB迁移替换至金仓数据库上线流程周期全解析
数据库·mongodb·文档型数据库