la restricción de clave externa de mysql está formada incorrectamente
Tengo dos tablas, table1
es la tabla padre con una columna ID
y table2
con una columna IDFromTable1
(no el nombre real) cuando pongo un FK en IDFromTable1
a ID
en table1
recibo el error Foreign key constraint is incorrectly formed error
. Me gustaría eliminar el registro de la tabla 2 si se elimina el registro table1
. Gracias por cualquier ayuda
ALTER TABLE `table2`
ADD CONSTRAINT `FK1`
FOREIGN KEY (`IDFromTable1`) REFERENCES `table1` (`ID`)
ON UPDATE CASCADE
ON DELETE CASCADE;
Avíseme si necesita alguna otra información. Soy nuevo en mysql
27 answers
Me encontré con este mismo problema con HeidiSQL. El error que recibes es muy críptico. Mi problema terminó siendo que la columna de clave externa y la columna de referencia no eran del mismo tipo o longitud.
La columna de clave externa era SMALLINT(5) UNSIGNED
y la columna referenciada era INT(10) UNSIGNED
. Una vez que hice ambos exactamente del mismo tipo, la creación de la clave externa funcionó perfectamente.
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-06-19 01:15:32
Tuve el mismo problema cuando se creó la tabla padre usando el motor MyISAM
. Es un error tonto, que arreglé con:
ALTER TABLE parent_table ENGINE=InnoDB;
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-12-14 18:37:46
Asegúrese de que las columnas son idénticas(del mismo tipo) y si la columna de referencia no es primary_key
, asegúrese de que es INDEXED
.
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-06-09 08:19:31
La sintaxis para definir claves foráneas es muy indulgente, pero para cualquier otra persona que se tropiece con esto, el hecho de que las claves foráneas deben ser "del mismo tipo" se aplica incluso a la intercalación, no solo al tipo de datos y la longitud y la firma de bits.
No es que mezcles la intercalación en tu modelo (¿lo harías?) pero si lo hace, asegúrese de que sus campos de clave primaria y foránea sean del mismo tipo de intercalación en phpmyadmin o Heidi SQL o lo que use.
Espero que esto le ahorre las cuatro horas de prueba y error me costó.
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-18 21:56:16
Solo para completar.
Este error también podría ser el caso si tiene una clave foránea con VARCHAR(..) y el conjunto de caracteres de la tabla referenciada es diferente de la tabla que la hace referencia.
Por ejemplo, VARCHAR(50) en una tabla Latin1 es diferente de VARCHAR(50) en una tabla UTF8.
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-02-18 14:43:44
Tuve el mismo problema, pero lo resolví.
Solo asegúrese de que la columna 'ID' en 'table1' tenga UNIQUE index!
Y por supuesto el tipo, longitud de las columnas 'ID' e 'IDFromTable1' en estas dos tablas tiene que ser el mismo. Pero ya sabes de esto.
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-09-01 19:20:19
Mysql error texts no ayuda tanto, en mi caso, la columna tenía "not null" restricción, por lo que el "on delete set null" no estaba permitido
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-26 08:20:19
Si todo está bien, simplemente agregue ->unsigned();
al final de foregin key
.
Si no funciona, compruebe el tipo de datos de ambos campos. deben ser los mismos.
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-06-01 10:37:51
Intenta ejecutar lo siguiente:
show create table Parent //and check if type for both tables are the same, like myISAM or innoDB, etc //Other aspects to check with this error message: the columns used as foreign keys must be indexed, they must be of the same type (if i.e one is of type smallint(5) and the other of type smallint(6), it won't work), and, if they are integers, they should be unsigned. //or check for charsets show variables like "character_set_database"; show variables like "collation_database"; //edited: try something like this ALTER TABLE table2 ADD CONSTRAINT fk_IdTable2 FOREIGN KEY (Table1_Id) REFERENCES Table1(Table1_Id) ON UPDATE CASCADE ON DELETE CASCADE;
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
2011-12-08 17:25:40
Tuve el mismo problema con Symfony 2.8.
No lo entendí al principio, porque no había problemas similares con la longitud int de las claves foráneas, etc.
Finalmente tuve que hacer lo siguiente en la carpeta del proyecto. (Un reinicio del servidor no ayudó!)
app/console doctrine:cache:clear-metadata
app/console doctrine:cache:clear-query
app/console doctrine:cache:clear-result
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-24 14:07:56
Gracias S Doerin:
"Sólo para completar. Este error también podría ser el caso si tiene una clave foránea con VARCHAR(..) y el conjunto de caracteres de la tabla referenciada es diferente de la tabla que la hace referencia. por ejemplo, VARCHAR (50) en una tabla Latin1 es diferente de VARCHAR(50) en una tabla UTF8."
Resolví este problema, cambiando el tipo de caracteres de la tabla. la creación tiene latin1 y la correcta es utf8.
Añade la siguiente línea. CARÁCTER PREDETERMINADO SET = utf8;
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-24 04:56:09
Tuve problemas al usar Alter table para agregar una clave foránea entre dos tablas y lo que me ayudó fue asegurarme de que cada columna a la que intentaba agregar una relación de clave foránea estuviera indexada. Para hacer esto en PHP MyAdmin: Vaya a la tabla y haga clic en la pestaña estructura. Haga clic en el índice opción para indexar la columna deseada como se muestra en la captura de pantalla:
Una vez que indexé ambas columnas que estaba tratando de hacer referencia con mis claves foráneas, pude usar con éxito la tabla alter y crear la relación de clave foránea. Verá que las columnas están indexadas como en la siguiente captura de pantalla:
Observe cómo aparece zip_code en ambas tablas.
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-12 22:40:49
Tuve los mismos problemas.
El problema es que la columna de referencia no es una clave primaria.
Haz que sea una clave primaria y el problema se resuelve.
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-02-17 17:59:25
Es necesario comprobar que ambos sean iguales en todas sus propiedades, inclusive en "Intercalación"
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-08-03 16:13:48
Compruebe el motor de tablas, ambas tablas tienen que ser el mismo motor, que me ayudó tanto.
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-09-13 12:14:47
Estaba usando HeidiSQL y para resolver este problema tuve que crear un índice en la tabla referenciada con todas las columnas referenciadas.
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-09 15:57:08
Tuve el mismo problema, ambas columnas eran INT(11) NO NULL pero no fui capaz de crear la clave foránea. Tuve que desactivar las comprobaciones de claves foráneas para ejecutarlo correctamente :
SET FOREIGN_KEY_CHECK=OFF;
ALTER TABLE ... ADD CONSTRAINT ...
SET FOREIGN_KEY_CHECK=ON;
Espero que esto ayude a alguien.
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
2018-02-05 16:02:21
Una causa probable más para la visualización de este error. El orden en el que estaba creando las tablas estaba equivocado. Estaba tratando de hacer referencia a una clave de una tabla que aún no se había creado.
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
2018-03-07 07:27:10
Tuve el mismo problema con Laravel 5.1 migration Schema Builder con MariaDB 10.1.
El problema era que había escrito unigned
en lugar de unsigned
(faltaba la letra s
) mientras configuraba la columna.
Después de corregir el error tipográfico se solucionó para mí.
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-12-01 16:58:25
Aunque las otras respuestas son bastante útiles, solo quería compartir mi experiencia también.
Me enfrenté al problema cuando eliminé una tabla cuya id
ya estaba siendo referenciada como clave foránea en otras tablas ( con datos) e intenté recrear/importar la tabla con algunas columnas adicionales.
La consulta para recreación (generada en phpMyAdmin) tenía el siguiente aspecto:
CREATE TABLE `the_table` (
`id` int(11) NOT NULL, /* No PRIMARY KEY index */
`name` varchar(255) NOT NULL,
`name_fa` varchar(255) NOT NULL,
`name_pa` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
... /* SOME DATA DUMP OPERATION */
ALTER TABLE `the_table`
ADD PRIMARY KEY (`id`), /* PRIMARY KEY INDEX */
ADD UNIQUE KEY `uk_acu_donor_name` (`name`);
Como puede notar, el índice PRIMARY KEY
se estableció después de la creación ( y inserción de datos) que estaba causando el problema.
Solución
La solución fue agregar el índice PRIMARY KEY
en la consulta de definición de tabla para el id
que se referenciaba como clave foránea, mientras que también lo eliminaba de la parte ALTER TABLE
donde se establecían los índices:
CREATE TABLE `the_table` (
`id` int(11) NOT NULL PRIMARY KEY, /* <<== PRIMARY KEY INDEX ON CREATION */
`name` varchar(255) NOT NULL,
`name_fa` varchar(255) NOT NULL,
`name_pa` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
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-08-23 13:04:13
Incluso me encontré con el mismo problema con mysql y liquibase. Así que este es el problema: La tabla de la que desea hacer referencia a una columna de otra tabla es diferente, ya sea en el caso del tipo de datos o en términos de tamaño del tipo de datos.
Error appears in below scenario:
Scenario 1:
Table A has column id, type=bigint
Table B column referenced_id type varchar(this column gets the value from the id column of Table A.)
Liquibase changeset for table B:
<changeset id="XXXXXXXXXXX-1" author="xyz">
<column name="referenced_id" **type="varchar"**>
</column>
</changeset>
<changeSet id="XXXXXXXXXXX-2" author="xyz">
<addForeignKeyConstraint constraintName="FK_table_A"
referencedTableName="A" **baseColumnNames="referenced_id**"
referencedColumnNames="id" baseTableName="B" />
</changeSet>
Table A changeSet:
<changeSet id="YYYYYYYYYY" author="xyz">
<column **name="id"** **type="bigint"** autoIncrement="${autoIncrement}">
<constraints primaryKey="true" nullable="false"/>
</column>
</changeSet>
Solution:
correct the type of table B to bigint because the referenced table has type bigint.
Scenrario 2:
The type might be correct but the size might not.
e.g. :
Table B : referenced column type="varchar 50"
Table A : base column type ="varchar 255"
Solution change the size of referenced column to that of base table's column size.
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-11-15 06:26:28
Perdí durante horas por eso!
PK en una tabla fue utf8
en otra fue utf8_unicode_ci
!
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
2018-01-23 15:34:08
Compruebe que ha especificado el nombre de la tabla en mayúsculas y minúsculas (si los nombres de las tablas distinguen entre mayúsculas y minúsculas en su base de datos). En mi caso tuve que cambiar
CONSTRAINT `FK_PURCHASE_customer_id` FOREIGN KEY (`customer_id`) REFERENCES `customer` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
A
CONSTRAINT `FK_PURCHASE_customer_id` FOREIGN KEY (`customer_id`) REFERENCES `CUSTOMER` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
Observe que customer
cambió a CUSTOMER
.
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
2018-02-19 13:17:14
Si usa phpMyAdmin puede omitir el problema desmarcando "Habilitar comprobaciones de claves foráneas" - entonces puede importar las tablas sin solucionar el problema.
Seguro que hay una manera de omitir las comprobaciones de claves foráneas con MySQL CLI
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
2018-03-27 15:56:38
O puede usar DBDesigner4 que tiene una interfaz gráfica para crear su base de datos y vincularlas usando FK. Haga clic derecho en su tabla y seleccione 'Copiar tabla SQL Crear' que crea el código.
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
2018-04-07 04:33:58
(Último reenvío) Incluso si el nombre del campo y el tipo de datos son los mismos pero la intercalación no es la misma, también dará lugar a ese problema.
Por Ejemplo
TBL NOMBRE / DATOS TIPO | COTEJO
ActivityID |INT / latin1_general_ci ActivityID |INT / utf8_general_ci
Pruebe Cambiarlo en
TBL NOMBRE / DATOS TIPO | COTEJO
ActivityID |INT / latin1_general_ci ActivityID |INT / latin1_general_ci
....
Esto funcionó para mí.
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
2018-05-01 09:47:51
Para aquellos que usan laravel, preste atención en sus migraciones cuando desee hacer la clave foránea en
"...references('the_column_name')->on('the_table_name)...",
in_table_name
, la migración que crea esta tabla se migrará antes de migrar esta migración.
Para que las migraciones funcionen correctamente, preste atención a su prioridad, cambie su prioridad cambiando sus nombres.
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
2018-09-16 23:15:33