How to set a FK value NULL upon receiving error for foreign key constraint?
Consider a simple table a
CREATE TABLE test
(
id int(11) NOT NULL AUTO_INCREMENT
ex_key int(11),
FOREIGN KEY(ex_key) REFERENCES ex_table(ex_key) ON DELETE SET NULL,
PRIMARY KEY (id)
)
If receiving FK error for an invalid ex_key
INSERT INTO test (id, ex_key) VALUES ('22', '22');
we can insert by setting NULL value for the foreign key
INSERT INTO test (id, ex_key) VALUES ('22', NULL);
It can be done by an IF statement, but is there a way to do so in the same query?
I hope to find a solution similar to available ON DUPLICATE KEY UPDATE for UNIQUE columns.