mysql外键的应用_MySQL外键应用

(4) 举例

实例一:

4.1

CREATE TABLE parent(id INT NOT NULL,

PRIMARY KEY (id)

) TYPE=INNODB; --type=innodb相当于engine=innodb

CREATE TABLE child(id INT, parent_id INT,

INDEX par_ind (parent_id),

FOREIGN KEY (parent_id) REFERENCES parent(id)

ON DELETE CASCADE

) TYPE=INNODB;

向parent插入数据后,向child插入数据,插入时,child中的parent_id的值只能是parent中有的数据,否则插入不成功;

删除parent记录时,child中的相应记录也会被删除;-->因为: on delete cascade

更新parent记录时,不给更新;-->因为没定义,默认采用restrict.

4.2

若child如下:

create table child(id int not null primary key auto_increment,parent_id int,

index par_ind (parent_id),

constraint fk_1 foreign key (parent_id) references

parent(id) on update cascade on delete restrict)

type=innodb;

用上面的:

1).

则可以更新parent记录时,child中的相应记录也会被更新;-->因为: on update cascade

2).

不能是子表操作,影响父表.只能是父表影响子表.

3).

删除外键:

alter table child drop foreign key fk_1;

4)

添加外键:

alter table child add constraint fk_1 foreign key (parent_id) references

parent(id) on update restrict on delete set null;

(5) 多个外键存在:

product_order表对其它两个表有外键。

一个外键引用一个product表中的双列索引。另一个引用在customer表中的单行索引:

CREATE TABLE product (category INT NOT NULL, id INT NOT NULL,

price DECIMAL,

PRIMARY KEY(category, id)) TYPE=INNODB;

CREATE TABLE customer (id INT NOT NULL,

PRIMARY KEY (id)) TYPE=INNODB;

CREATE TABLE product_order (no INT NOT NULL AUTO_INCREMENT,

product_category INT NOT NULL,

product_id INT NOT NULL,

customer_id INT NOT NULL,

PRIMARY KEY(no),

-- 双外键

INDEX (product_category, product_id),

FOREIGN KEY (product_category, product_id)

REFERENCES product(category, id)

ON UPDATE CASCADE ON DELETE RESTRICT,

-- 单外键

INDEX (customer_id),

FOREIGN KEY (customer_id)

REFERENCES customer(id)) TYPE=INNODB;

(6) 说明:

1.若不声明on update/delete,则默认是采用restrict方式.

2.对于外键约束,最好是采用: ON UPDATE CASCADE ON DELETE RESTRICT 的方式.0b1331709591d260c1c78e86d0c51c18.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值