![]() ( 'ACME Sales', '5000 North 1st Street CA 95134') Code language: SQL (Structured Query Language) ( sql ) VALUES( 'ACME Headquaters', '3950 North 1st Street CA 95134'), ![]() Insert rows into the buildings table: INSERT INTO buildings(building_name,address) Notice that the ON DELETE CASCADE clause at the end of the foreign key constraint definition. Create the rooms table: CREATE TABLE rooms ( ) Code language: SQL (Structured Query Language) ( sql ) Create the buildings table: CREATE TABLE buildings (īuilding_no INT PRIMARY KEY AUTO_INCREMENT, The following are steps that demonstrate how the ON DELETE CASCADE referential action works. ![]() You also want the rows in the rooms table that refers to building number 2 will be also removed. WHERE building_no = 2 Code language: SQL (Structured Query Language) ( sql ) 2 in the buildings table as the following query: DELETE FROM buildings For example, when you delete a row with building no. When you delete a row from the buildings table, you also want to delete all rows in the rooms table that references to the row in the buildings table. The relationship between the buildings and rooms tables is one-to-many (1:N) as illustrated in the following database diagram: A room would not exist without a building. However, each room belongs to one only one building. In this database model, each building has one or many rooms. Suppose that we have two tables: buildings and rooms. Let’s take a look at an example of using MySQL ON DELETE CASCADE. However, MySQL provides a more effective way called ON DELETE CASCADE referential action for a foreign key that allows you to delete data from child tables automatically when you delete the data from the parent table. In the previous tutorial, you learned how to delete data from multiple related tables using a single DELETE statement. Summary: in this tutorial, you will learn how to use MySQL ON DELETE CASCADE referential action for a foreign key to delete data from multiple related tables.
0 Comments
Leave a Reply. |