[SQL] - integrity constraint violation

当修改资料库资料,违反资料表之间的关联性,可能就会遇到 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);

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章