I have two MySQL tables: collections
and privacy_level
.
I define them with a foreign key relationship as such:
CREATE TABLE collections ( coll_id smallint NOT NULL AUTO_INCREMENT UNSIGNED, name varchar(30) NOT NULL, privacy tinyint NOT NULL UNSIGNED DEFAULT '0', PRIMARY KEY(coll_id), INDEX(privacy), FOREIGN KEY fk_priv (privacy) REFERENCES privacy_level (level) ON UPDATE CASCADE ON DELETE RESTRICT ) ENGINE=InnoDB; CREATE TABLE privacy_level ( level tinyint NOT NULL UNSIGNED, name varchar(20) NOT NULL, PRIMARY KEY (level) ) ENGINE InnoDB;
My question is about the ON DELETE RESTRICT
clause and I couldn't derive the answer from the online manual or a google search.
Does this mean that I can never delete a row from privacy_level
?
Or, does it mean that I can't delete a row from privacy_level
if a row from collections.privacy
has a value that is the same as a value in privacy_level.level
?
That is, if privacy_level
has level = 2
, name = 'top secret'
but no entry in collections.Privacy has privacy = 2
, can I delete the level = 2
, name = 'top secret'
entry? Or is it forbidden on a column wide basis?
Thanks for any insight.
The ON DELETE clause says that if a particular primary key ID value in the CUSTOMERS table is deleted, this action shall be prevented (this is the "restrict" part) if there is any row in the ORDERS table which has a foreign key that matches the value of the CUSTOMER table ID value.
Foreign key constraints are subject to the following conditions and restrictions: Parent and child tables must use the same storage engine, and they cannot be defined as temporary tables. Creating a foreign key constraint requires the REFERENCES privilege on the parent table.
What does an "ON DELETE CASCADE" clause imply in a foreign key constraint in a MySQL CREATE TABLE statement? When a row in the parent table is deleted all the rows in a child table that point to that row via a foreign key are deleted.
The delete rule of NO ACTION is checked to enforce that any non-null foreign key refers to an existing parent row after the other referential constraints have been enforced. The delete rule of a referential constraint applies only when a row of the parent table is deleted.
ON DELETE RESTRICT
means you can't delete a given parent row if a child row exists that references the value for that parent row. If the parent row has no referencing child rows, then you can delete that parent row.
ON DELETE RESTRICT
is pretty much superfluous syntax, because this is the default behavior for a foreign key anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With