Agregar Clave externa a la tabla existente
Quiero añadir una clave Foránea a una tabla llamada "katalog".
ALTER TABLE katalog
ADD CONSTRAINT `fk_katalog_sprache`
FOREIGN KEY (`Sprache`)
REFERENCES `Sprache` (`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL;
Cuando intento hacer esto, recibo este mensaje de error:
Error Code: 1005. Can't create table 'mytable.#sql-7fb1_7d3a' (errno: 150)
Error en el estado INNODB:
120405 14:02:57 Error en la restricción de clave foránea de la tabla mytable.# sql-7fb1_7d3a:
FOREIGN KEY (`Sprache`)
REFERENCES `Sprache` (`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL:
Cannot resolve table name close to:
(`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL
Cuando uso esta consulta funciona, pero con una acción incorrecta "al eliminar":
ALTER TABLE `katalog`
ADD FOREIGN KEY (`Sprache` ) REFERENCES `sprache` (`ID` )
Ambas tablas son InnoDB y ambos campos son "INT(11) not null". Estoy usando MySQL 5.1.61. Tratando de dispara esta consulta ALTER con MySQL Workbench (más reciente) en un MacBook Pro.
Table Create Statements:
CREATE TABLE `katalog` (
`ID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`Name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`AnzahlSeiten` int(4) unsigned NOT NULL,
`Sprache` int(11) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `katalogname_uq` (`Name`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC$$
CREATE TABLE `sprache` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Bezeichnung` varchar(45) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `Bezeichnung_UNIQUE` (`Bezeichnung`),
KEY `ix_sprache_id` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
8 answers
Para agregar una clave foránea (grade_id) a una tabla existente (users), siga los siguientes pasos:
ALTER TABLE users ADD grade_id SMALLINT UNSIGNED NOT NULL DEFAULT 0;
ALTER TABLE users ADD CONSTRAINT fk_grade_id FOREIGN KEY (grade_id) REFERENCES grades(id);
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
2015-07-18 22:38:10
Simplemente use esta consulta, la he probado según mi escenario y funciona bien
ALTER TABLE katalog ADD FOREIGN KEY (`Sprache`) REFERENCES Sprache(`ID`);
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
2014-01-28 12:05:47
Compruebe este enlace. Me ha ayudado con errno 150: http://verysimple.com/2006/10/22/mysql-error-number-1005-cant-create-table-mydbsql-328_45frm-errno-150/
En la parte superior de mi cabeza me vienen a la mente dos cosas.
- ¿Es su índice de clave foránea un nombre único en toda la base de datos (#3 en la lista)?
- ¿Está tratando de establecer la tabla PK en NULL en la actualización (#5 en la lista)?
Supongo que el problema es con el conjunto NULL en la actualización (si mis cerebros no están al revés hoy como lo están tan a menudo...).
Edit: Me perdí los comentarios en tu post original. Unsigned / not unsigned int columns tal vez resolvió su caso. Espero que mi enlace ayude a alguien en el pensamiento futuro.
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
2012-04-05 13:19:53
Pasos Sencillos...
ALTER TABLE t_name1 ADD FOREIGN KEY (column_name) REFERENCES t_name2(column_name)
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-10-06 07:23:04
FOREIGN KEY (`Sprache`)
REFERENCES `Sprache` (`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL;
Pero tu mesa tiene:
CREATE TABLE `katalog` (
`Sprache` int(11) NOT NULL,
It no puede establecer el Sprache de columna en NULL porque está definido como NOT NULL.
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-04-01 17:12:08
Cuando agregue una restricción de clave foránea a una tabla usando ALTER TABLE, recuerde crear primero los índices requeridos.
- Crear índice
- Altera la tabla
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
2012-04-05 12:25:48
MySQL ejecutará esta consulta:
ALTER TABLE `db`.`table1`
ADD COLUMN `col_table2_fk` INT UNSIGNED NULL,
ADD INDEX `col_table2_fk_idx` (`col_table2_fk` ASC),
ADD CONSTRAINT `col_table2_fk1`
FOREIGN KEY (`col_table2_fk`)
REFERENCES `db`.`table2` (`table2_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
Salud!
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-01-31 07:56:36
Prueba todo en una consulta
ALTER TABLE users ADD grade_id SMALLINT UNSIGNED NOT NULL DEFAULT 0,
ADD CONSTRAINT fk_grade_id FOREIGN KEY (grade_id) REFERENCES grades(id);
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-05-08 19:24:25