概述
約束示例?
完成以下案例:
create table user (id int primary key auto_increment comment '主鍵',name varchar(10) not null unique comment '姓名',age tinyint unsigned check ( age > 0 and age <= 120 ) comment '年齡',status char(1) default '1' comment '狀態',gender char(1) comment '性別'
) comment '用戶表';
外鍵約束
概念
圖中的父表也叫主表,子表也叫從表。
如果某一個表A有一個字段的值來自于另一個表B的主鍵,那么表A就是子表(從表),表B就是父表(主表)。
?添加外鍵的語法
-- 創建部門表
create table if not exists dept
(id int auto_increment primary key comment 'ID',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 primary key comment 'ID',name varchar(50) not null comment '姓名',age tinyint unsigned 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, '2008-11-05', 2, 1),(4, '韋一笑', 40, '開發', 11000, '2003-06-15', 2, 1),(5, '常遇春', 43, '開發', 10500, '2004-07-05', 3, 1),(6, '小昭', 25, '測試', 7000, '2009-12-10', 2, 1);-- 給員工表添加外鍵
-- (dept_id) 表示將員工表的dept_id字段作為外鍵字段
-- references dept(id)表示員工表中的外鍵字段關聯自部門表的id字段
alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references dept(id);-- 刪除員工表中名為fk_emp_dept_id的外鍵
alter table emp drop foreign key fk_emp_dept_id;
?外鍵的刪除和更新操作
-- 添加外鍵,當父表有刪除或更新操作時,子表級聯刪除和級聯更新
alter table emp add constraint fk_emp_dept_id foreign key (dept_id)references dept(id) on update cascade on delete cascade;