mysql 外键约束(foreign key)是表的一个特殊字段,经常与主键约束一起使用。对于两个具有关联关系的表而言,相关联字段中主键所在的表就是主表(父表),外键所在的表就是从表(子表)。
在创建表时设置外键约束
在 create table 语句中,通过 foreign key 关键字来指定外键,具体的语法格式如下:
[constraint <外键名>] foreign key 字段名 [,字段名2,…]references <主表名> 主键列1 [,主键列2,…]
示例
为了展现表与表之间的外键关系,本例在 test_db 数据库中创建一个部门表 tb_dept1,表结构如下表所示。
字段名称数据类型备注
id int(11) 部门编号
name varchar(22) 部门名称
location varchar(22) 部门位置
创建 tb_dept1 的 sql 语句和运行结果如下所示。
mysql> create table tb_dept1 -> ( -> id int(11) primary key, -> name varchar(22) not null, -> location varchar(50) -> );query ok, 0 rows affected (0.37 sec)
创建数据表 tb_emp6,并在表 tb_emp6 上创建外键约束,让它的键 deptid 作为外键关联到表 tb_dept1 的主键 id,sql 语句和运行结果如下所示。
mysql> create table tb_emp6 -> ( -> id int(11) primary key, -> name varchar(25), -> deptid int(11), -> salary float, -> constraint fk_emp_dept1 -> foreign key(deptid) references tb_dept1(id) -> );query ok, 0 rows affected (0.37 sec)mysql> desc tb_emp6;+--------+-------------+------+-----+---------+-------+| field | type | null | key | default | extra |+--------+-------------+------+-----+---------+-------+| id | int(11) | no | pri | null | || name | varchar(25) | yes | | null | || deptid | int(11) | yes | mul | null | || salary | float | yes | | null | |+--------+-------------+------+-----+---------+-------+4 rows in set (1.33 sec)
以上语句执行成功之后,在表 tb_emp6 上添加了名称为 fk_emp_dept1 的外键约束,外键名称为 deptid,其依赖于表 tb_dept1 的主键 id。
注意:从表的外键关联的必须是主表的主键,且主键和外键的数据类型必须一致。例如,两者都是 int 类型,或者都是 char 类型。如果不满足这样的要求,在创建从表时,就会出现“error 1005(hy000): can't create table”错误。
推荐教程:mysql视频教程
以上就是mysql建表外键怎么设?的详细内容。