How to update foreign key value when parent row is deleted in mysql?

mysql foreign-keys

71 просмотра

1 ответ

I want to update the foreign key value when parent row is deleted.

There is a "SET NULL" option in phpmyadmin, but instead of setting the value to null, I want to set it to something I want.

How can I do this?

Автор: RezaT1994 Источник Размещён: 08.11.2019 11:07

Ответы (1)


2 плюса

Решение

There's no auto-magical built-in way of doing this like the set null option, but you could always write a trigger with your specific business logic:

DELIMITER //

CREATE TRIGGER parent_delete_tr
BEFORE DELETE
    ON parent FOR EACH ROW

    BEGIN
        UPDATE children
        SET    parent_id = 123 -- Or some other logic
        WHERE  parent_id = OLD.id;
    END; //

DELIMITER ;
Автор: Mureinik Размещён: 20.08.2016 09:37
Вопросы из категории :
32x32