首先谈一下外键的作用,一是节省空间,二是约束含外键的列中的值,含外键列的值必须为参考列中的id
创建数据表时,创建外键方法
create table userinfo(
uid bigint auto_increment primary key, # 创建列uid ,bigint类型,自增,主键
name varchar(32), # 创建列name varchar类型,32位
department_id int,
xx_id int,
constraint fk_user_depar foreign key (department_id) references department(id) #创建外键
)engine=innodb default charset=utf8;
create table department(
id bigint auto_increment primary key,
title char(15)
)engine=innodb default charset=utf8;
创建外键语法如下
constraint fk_user_depar foreign key (department_id) references department(id)
constraint 外键名字 foreign key (添加外键的列名)references 参考表的名称(参考表中的列名)
外键也可以是两列,但是前提条件是,被参考的表的两列均是主键
CREATE TABLE t5 (
nid int(11) NOT NULL AUTO_INCREMENT,
pid int(11) not NULL,
num int(11),
primary key(nid,pid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
create table t6(
id int auto_increment primary key,
name char(10),
id1 int,
id2 int,
CONSTRAINT fk_t5_t6 foreign key (id1,id2) REFERENCES t5(nid,pid)
)engine=innodb default charset=utf8;