MySQL基础-约束

77 阅读2分钟

约束作用于表中的字段上,反正就是对表中字段对应的数据进行一些约束,在建表和修改表的时候都能使用

约束描述关键字
非空约束数据不为nullNOT NULL
唯一约束数据唯一UNIQUE
主键约束一行数据的唯一标识,非空且唯一PRIMARY KEY
默认约束设默认值DEFAULT
检查约束条件约束CHECK
外键约束至少两张表,使两张表建立连接FOREIGN KEY

约束案例

# 创建表,AUTO_INCREMENT表示自增
create table user(
    id int PRIMARY KEY AUTO_INCREMENT comment 'ID唯一表示',
    name varchar(10) not null unique comment '姓名',
    age int check ( age>0 and age <= 120 ) comment '年龄',
    status char(1) default '1' comment 'status',
    gender char(1) comment '性别'
)comment '用户表';

# 插入数据
insert into user(name,age,status,gender) values('Tom1',19,'1','男'),('Tom2',12,'0','男');

外键约束

数据准备

# 创建部门表
create table dept(
    id int auto_increment comment 'ID' primary key,
    name varchar(50) not null comment '部门名称'
)comment '部门表';

INSERT INTO dept (id, name) VALUES (1, '研发部'), (2, '市场部'),(3, '财务部'), (4, '销售部'), (5, '总经办');

create table emp(
    id int auto_increment comment 'ID' primary key, name varchar(50) not null comment '姓名',
    age int comment '年龄',
    job varchar(20) comment '职位',
    salary int comment '薪资',
    entrydate date comment '入职时间',
    managerid int comment '直属领导ID',
    dept_id int comment '部门ID'
)comment '员工表';

INSERT INTO emp (id, name, age, job,salary, entrydate, managerid, dept_id)
VALUES
(1, '金庸', 66, '总裁',20000, '2000-01-01', null,5),(2, '张无忌', 20, '项目经理',12500, '2005-12-05', 1,1),
(3, '杨逍', 33, '开发', 8400,'2000-11-03', 2,1),(4, '韦一笑', 48, '开 发',11000, '2002-02-05', 2,1),
(5, '常遇春', 43, '开发',10500, '2004-09-07', 3,1),(6, '小昭', 19, '程 序员鼓励师',6600, '2004-10-12', 2,1);

语法

外键有删除\更新行为,就是你在删除或者更新父表时,若存在外键应该怎么做

标题说明
NO ACTION有外键关联,不允许删除或更新
RESTRICT同NO ACTION
CASCADE同时删除关联数据
SET NULL关联的键设为null
create table 表名(
    字段名 数据类型,
    ...
    [constraint] [外键名称] FOREIGN KEY (外键字段名) REFERENCES 主表(主表列名)
);

ALTER TABLE 表名 ADD CONSTRAINT 外键名称 FOREIGN KEY(外键字段名) REFERENCES 主表(主表列名) [ON UPDATE 更新行为] [ON DELETE 删除行为];

ALTER TABLE 表名 DROP FOREIGN KEY 外键名称;

外键约束案例

#添加外键,外键名称是用于删除用的
alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references dept(id) ON UPDATE CASCADE ON DELETE NO ACTION;

#删除外键
alter table emp drop foreign key fk_emp_dept_id;