当修改资料库资料,违反资料表之间的关联性,可能就会遇到 integrity constraint violation 问题。
常见的有这三种:
foreign key constraintunique constraintcheck constraint今天要分享的是 foreign key contraint,发生在删除资料时,child table 发生了 initegrity constraint violation 问题,也就是其 referenced 的资料将要被删除,但仍然被 child table referencing。
解决办法即是在 child table 的 foreign key 加上 cascade on delete,当 parent table 删资料时,child table 的资料也会被删除。
範例: cascade on delete
CREATE TABLE orders ( order_id int NOT NULL AUTO_INCREMENT, customer_id int NOT NULL, order_date date, PRIMARY KEY (order_id), FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ON DELETE CASCADE);CREATE TABLE order_items ( item_id int NOT NULL AUTO_INCREMENT, order_id int NOT NULL, item_name varchar(255), quantity int, PRIMARY KEY (item_id), FOREIGN KEY (order_id) REFERENCES orders(order_id) ON DELETE CASCADE);