使用外键 (数据表的引擎需要用 InnoDB)
简单说明:
商品表 主键列 (id)
通常在设置热销商品时 我比较喜欢 在创建一个 热销商品表 来保存商品的 主键(id)
热销商品表 外键列 (pid)
假设 商品id 为 10 的商品设置过热销商品。 在之后 删除商品id 为 10 的商品时 需要吧热销商品中的 商品id 为10 的记录也需要一起处理。
否则热销商品表中会残留垃圾数据。
此时 如果没有外键 我们应当执行2次 delete 语句。
使用外键,那么我们的热销商品表代码需要这样
// 商品表
create table product(
id int unsigned not null auto_increment primary key,
name varchar(255) not null
);
// 热销商品表
create table hot_product(
id int unsigned not null auto_increment primary key,
pid int unsigned not null,
index(pid),
constraint pid_fk foreign key(pid) references product(id) on delete cascade
)
constraint pid_fk foregin key(pid) references product(id) on delete cascade
其中 pid_fk 只是外键约束的名 foreig key(pid) 是 热销商品中 需要和商品表关联其来的外键列
最后 on delete cascade 是 当 商品表 (product)表中发生删除操作时 如果 外键表 (hot_product)表中存在被删除的外键id 则一起删除。
这样我们能够省略删除热销商品表数据的过程。
另外还有 on update cascade 在主键表中修改时 外进表的列也会自动被修改
在已有的表中增加外键
alter table 表名 add constraint fk_name foreign key(字段) references 主键表名(字段名) on delete cascade;
删除外键
alter table 表名 drop foreign key 外键名