Q1: Table restrict for delete, if child table have records.
Q2: Mysql constraint restrict.
Q3. How to prevent from delete a parent record, if child exists.
Create a table products
Create a table reviews, as each products have one or more reviews
Now, if you try to delete a product having one or more review(s), you will get an mysql error similar to following.
Error
SQL query:
DELETE FROM `products` WHERE `products`.`id` =1
MySQL said:
#1451 - Cannot delete or update a parent row: a foreign key constraint fails (`abc`.`reviews`, CONSTRAINT `reviews_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`))
You can only delete the product, after deleted its reviews.
Q2: Mysql constraint restrict.
Q3. How to prevent from delete a parent record, if child exists.
Above all Questions have only one answer that is below with fine example.
Create a table products
CREATE TABLE products (
id int(11) unsigned not null primary key AUTO_INCREMENT,
name varchar(255) default null
)
Create a table reviews, as each products have one or more reviews
CREATE TABLE reviews (
id int unsigned not null primary key AUTO_INCREMENT,
review_by int(11) unsigned not null,
product_id int(11) unsigned not null,
FOREIGN KEY (product_id) REFERENCES products (id) ON DELETE RESTRICT ON UPDATE RESTRICT
)
Now, if you try to delete a product having one or more review(s), you will get an mysql error similar to following.
Error
SQL query:
DELETE FROM `products` WHERE `products`.`id` =1
MySQL said:
#1451 - Cannot delete or update a parent row: a foreign key constraint fails (`abc`.`reviews`, CONSTRAINT `reviews_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`))
You can only delete the product, after deleted its reviews.
0 Comment:
Post a Comment