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; 
相关推荐
weixin_397574091 小时前
用自然语言查数据库出图表靠谱吗?一次智能问数实践复盘
数据库
字节跳动开源3 小时前
Viking AI 搜索 CLI 正式发布:会说话,就能做搜索推荐
数据库·人工智能·开源
TechWJ4 小时前
数据库在公司内网,出差路上想查数据怎么办?
服务器·数据库·mariadb
我是一颗柠檬4 小时前
【MySQL全面教学】MySQL事务与ACID Day9(2026年)
数据库·后端·mysql
橙子圆1234 小时前
Redis知识9之集群
数据库·redis·缓存
BlackHeart12034 小时前
【SQL】Oracle中序列(Sequence)作为默认值引发的ORA-00979
数据库·sql·oracle
rocpp5 小时前
Android 相册选择与拍照接入实践:MediaStore 分页、权限适配与 FileProvider
android
bug菌5 小时前
【SpringBoot 3.x 第254节】夯爆了,数据库访问性能优化实战详解!
数据库·spring boot·后端
xxl大卡5 小时前
MySQL的执行流程
数据库·mysql
chicheese5 小时前
MySQL优化实践:选错JOIN 驱动表,性能相差几十倍
数据库·mysql