外键约束

CREATE TABLE yg(
id INT PRIMARY KEY auto_increment,
ename VARCHAR(30) NOT null,
age INT default 0,
dep_id int,
-- 添加外键 dep_id,关联dep表的id主键
-- 将yg的dep_id外键 关联到bm的 id主键
CONSTRAINT fk_yg_bm FOREIGN KEY(dep_id) REFERENCES bm(id)
);

CREATE table bm(
id int PRIMARY KEY auto_increment,
dep_name VARCHAR(30),
addr VARCHAR(30)
);
-- 员工
SELECT * FROM yg;

INSERT INTO yg VALUES
 (null,'孙琪',21,1), 
(null,'江西',19,1),
(null,'张三',29,1), 
(null,'王琪',23,1),
(null,'李四',13,2), 
(null,'九新',18,2),
(null,'kris',23,2);
-- 删除表
drop TABLE 	if EXISTS bm;

-- 部门
SELECT * FROM bm;

INSERT into bm VALUES 
(null,'研发部','广州'),

(null,'销售部','深圳');

您可能还喜欢...