I want to create a foreign key for a table using ON DELETE SET NULL
, but the ALTER
command is rejected.
CREATE TABLE `Locations` (
`id` int(0) NOT NULL,
`name` varchar(255) NOT NULL,
`image_id` int(0) UNSIGNED NULL DEFAULT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `Pictures` (
`id` int(0) NOT NULL,
`url` varchar(255) NULL,
PRIMARY KEY (`id`)
);
ALTER TABLE `Locations`
ADD CONSTRAINT `fk1` FOREIGN KEY (`image_id`) REFERENCES `Pictures` (`id`) ON DELETE SET NULL;
I found out so far, that there's already a BugReport in MySQL, but got closed as "expected behaviour": https://bugs.mysql.com/bug.php?id=80052 referenced here: https://stackoverflow.com/a/35042002/2889265
My question is now, how can I implement a field in Locations which might by filled with a reference to a row in Pictures using the primary key. But it's not required to be filled. The field might stay empty or is updated to be empty later on. (The location does no need to be pictured)
If that row in Pictures is deleted, the column in Locations should be resetted to NULL automatically (like i would expect the ON DELETE SET NULL function)? Do i have to build a trigger or something like that to achieve my expected behaviour.
Environments:
Dev: MariaDB 10.3.15
Prod: MySQL 8.0.2