约束条件二
foreign key,外键
先建被关联的表,并且被关联字段唯一
create table dep( id int unique not null, name char(10), comment char(50) );
再创建关联表
create table emp( id int primary key, name char(10), sex enum('male','female'), dep_id int, foreign key(dep_id) references dep(id));
查看表结构
mysql> desc emp; +--------+-----------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------+-----------------------+------+-----+---------+-------+ | id | int(11) | NO | PRI | NULL | | | name | char(10) | YES | | NULL | | | sex | enum('male','female') | YES | | NULL | | | dep_id | int(11) | YES | MUL | NULL | | +--------+-----------------------+------+-----+---------+-------+ 4 rows in set (0.00 sec)
先插入被关联表数据,再插入关联表数据
删除先删除关联表数据,再删除被关联表数据。
建立关联表时添加
on delete cascade #删除同步
on update cascade#更新同步