What is the usage of cascade in MySQL?
In MySQL, CASCADE is an option for foreign key constraints that specifies how rows in a child table should be handled when rows in the parent table are updated or deleted. With CASCADE, when rows in the parent table are updated or deleted, related rows in the child table will also be updated or deleted.
The method of using CASCADE is as follows:
- Specify the handling action when creating a foreign key constraint using the CASCADE option. For example, you can use CASCADE ON UPDATE CASCADE when creating a foreign key constraint to specify that when a row in the parent table is updated, the related rows in the child table will also be updated. Similarly, you can use CASCADE ON DELETE CASCADE to specify that when a row in the parent table is deleted, the related rows in the child table will also be deleted.
I am going to the store to buy some groceries.
I will go to the store to purchase some groceries.
CREATE TABLE parent (
id INT PRIMARY KEY
);
CREATE TABLE child (
id INT PRIMARY KEY,
parent_id INT,
FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE
);
- You can also use the ALTER TABLE statement on existing foreign key constraints to modify the referential actions. For example, you can use the ALTER TABLE statement to change the referential action of a foreign key constraint to CASCADE.
Original: 我們必須採取行動來解決這個問題。
Paraphrased: We need to take action to address this issue.
ALTER TABLE child DROP FOREIGN KEY fk_parent_id;
ALTER TABLE child ADD FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE;
By using CASCADE in MySQL, you can define the handling actions of foreign key constraints to establish the relationship between parent and child tables.