MySQL on delete cascade. Test Example

做~自己de王妃 提交于 2019-11-27 08:16:14

Answer d. is correct, if and only if the storage engine actually supports and enforces foreign key constraints.

If the tables are created with Engine=MyISAM, then neither b. or d. is correct.

If the tables are created with Engine=InnoDB, then d. is correct.

NOTE:

This is true for InnoDB if and only if FOREIGN_KEY_CHECKS = 1; if FOREIGN_KEY_CHECKS = 0, then a DELETE from the parent table (foo) will not remove rows from the child table (foo2) that reference a row removed from the parent table.

Verify this with the output from SHOW VARIABLES LIKE 'foreign_key_checks' (1=ON, 0=OFF) (The normal default is for this to be ON.)

The output from SHOW CREATE TABLE foo will show which engine the table uses.

The output from SHOW VARIABLES LIKE 'storage_engine' will show the default engine used when a table is created and the engine is not specified.

You do have a relationship between two tables, it's in the foo2 creation command: ... foo_id int references foo(id) on delete cascade.

According to the MySQL Foreign Key Constraints reference:

CASCADE: Delete or update the row from the parent table, and automatically delete or update the matching rows in the child table. Both ON DELETE CASCADE and ON UPDATE CASCADE are supported.

Also, according to the MySQL Foreign Keys reference:

For storage engines other than InnoDB, it is possible when defining a column to use a REFERENCES tbl_name(col_name) clause, which has no actual effect, and serves only as a memo or comment to you that the column which you are currently defining is intended to refer to a column in another table.

So since the foreign key is from the child table to the parent table, it makes foo a parent table and foo2 a child table, so deleting a row from foo will cascade deletions to foo2, providing you use InnoDB or some other storage engine that supports it.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!