¿Cómo cambiar la acción referencial de clave foránea? (comportamiento)


He configurado una tabla que contiene una columna con una clave foránea, establecida en ON DELETE CASCADE (eliminar hijo cuando se elimina padre)

¿Cuál sería el comando SQL para cambiar esto a ON DELETE RESTRICT? (no se puede eliminar padre si tiene hijos)

Author: Moak, 2010-07-29

5 answers

Vieja pregunta pero agregando respuesta para que uno pueda obtener ayuda

Su proceso de dos pasos:

Supongamos que un table1 tiene una clave externa con nombre de columna fk_table2_id, con restricción nombre fk_name y table2 se refiere a la tabla con clave t2 (algo como abajo en mi diagrama ).

   table1 [ fk_table2_id ] --> table2 [t2]

Primer paso , ELIMINAR la RESTRICCIÓN antigua: (referencia)

ALTER TABLE `table1` 
DROP FOREIGN KEY `fk_name`;  

la restricción de aviso es eliminado, la columna no se elimina

Segundo paso , AGREGUE una nueva RESTRICCIÓN:

ALTER TABLE `table1`  
ADD CONSTRAINT `fk_name` 
    FOREIGN KEY (`fk_table2_id`) REFERENCES `table2` (`t2`) ON DELETE CASCADE;  

adición de restricción, columna ya está allí

Ejemplo:

Tengo una tabla UserDetails se refiere a la tabla Users:

mysql> SHOW CREATE TABLE UserDetails;
:
:
 `User_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`Detail_id`),
  KEY `FK_User_id` (`User_id`),
  CONSTRAINT `FK_User_id` FOREIGN KEY (`User_id`) REFERENCES `Users` (`User_id`)
:
:

Primer paso:

mysql> ALTER TABLE `UserDetails` DROP FOREIGN KEY `FK_User_id`;
Query OK, 1 row affected (0.07 sec)  

Segundo paso:

mysql> ALTER TABLE `UserDetails` ADD CONSTRAINT `FK_User_id` 
    -> FOREIGN KEY (`User_id`) REFERENCES `Users` (`User_id`) ON DELETE CASCADE;
Query OK, 1 row affected (0.02 sec)  

Resultado:

mysql> SHOW CREATE TABLE UserDetails;
:
:
`User_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`Detail_id`),
  KEY `FK_User_id` (`User_id`),
  CONSTRAINT `FK_User_id` FOREIGN KEY (`User_id`) REFERENCES 
                                       `Users` (`User_id`) ON DELETE CASCADE
:
 132
Author: Grijesh Chauhan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-30 05:59:07

Puedes hacer esto en una consulta si estás dispuesto a cambiar su nombre:

ALTER TABLE table_name
  DROP FOREIGN KEY `fk_name`,
  ADD CONSTRAINT `fk_name2` FOREIGN KEY (`remote_id`)
    REFERENCES `other_table` (`id`)
    ON DELETE CASCADE;

Esto es útil para minimizar el tiempo de inactividad si tiene una tabla grande.

 10
Author: Romuald Brunet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-17 13:00:06
ALTER TABLE DROP FOREIGN KEY fk_name;
ALTER TABLE ADD FOREIGN KEY fk_name(fk_cols)
            REFERENCES tbl_name(pk_names) ON DELETE RESTRICT;
 10
Author: pascal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-06 19:37:28

Recuerde que MySQL mantiene un índice simple en una columna después de eliminar la clave foránea. Por lo tanto, si necesita cambiar la columna 'referencias' debe hacerlo en 3 pasos

  • drop original FK
  • soltar un índice (nombres como fk anterior, usando drop index cláusula)
  • crear nuevo FK
 3
Author: Vasiliy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-04 20:47:32

Simplemente puede usar una consulta para gobernarlas todas: ALTER TABLE products DROP FOREIGN KEY oldConstraintName, ADD FOREIGN KEY (product_id, category_id) REFERENCES externalTableName (foreign_key_name, another_one_makes_composite_key) ON DELETE CASCADE ON UPDATE CASCADE

 3
Author: stamster,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-31 14:36:39