mercredi 4 février 2015

MySQL - Cannot add new Foreign Key


I'm using magento and it does some re-index for a product flat table structure. In this process a new table is created. The SQL for that table is something like:



CREATE TABLE `mg_catalog_product_flat_1` (
`entity_id` int UNSIGNED NOT NULL COMMENT 'entity_id' ,
`attribute_set_id` smallint UNSIGNED NOT NULL default '0' COMMENT 'attribute_set_id' ,
`type_id` varchar(32) NOT NULL default 'simple' COMMENT 'type_id' ,
`created_at` timestamp NULL default NULL COMMENT 'created_at' ,
`description` text NULL COMMENT 'description' ,
`updated_at` timestamp NULL default NULL COMMENT 'updated_at' ,
`url_key` varchar(255) NULL COMMENT 'url_key' ,
`url_path` varchar(255) NULL COMMENT 'url_path' ,
`visibility` smallint UNSIGNED NULL COMMENT 'visibility' ,
`weight` decimal(12,4) NULL COMMENT 'weight' ,
PRIMARY KEY (`entity_id`),
CONSTRAINT `FK_MG_MG_CAT_PRD_FLAT_1_ENTT_ID_MG_CAT_PRD_ENTT_ENTT_ID` FOREIGN KEY (`entity_id`) REFERENCES `mg_catalog_product_entity` (`entity_id`) ON DELETE CASCADE ON UPDATE CASCADE) COMMENT='Catalog Product Flat (Store 1)' ENGINE=INNODB charset=utf8 COLLATE=utf8_general_ci


When I run the query above I get this error:



SQLSTATE[HY000]: General error: 1005 Can't create table 'mylal_mage233.mg_catalog_product_flat_1' (errno: 121), query was:


If I create the table without the FK, it runs just fine. If I try and add the FK after with this SQL:



ALTER TABLE `mg_catalog_product_flat_1` ADD CONSTRAINT `FK_MG_MG_CAT_PRD_FLAT_1_ENTT_ID_MG_CAT_PRD_ENTT_ENTT_ID` FOREIGN KEY (`entity_id`) REFERENCES `mg_catalog_product_entity` (`entity_id`) ON DELETE CASCADE ON UPDATE CASCADE


I will get this error:



SQLSTATE[HY000]: General error: 1005 Can't create table 'mylal_mage233.#sql-4497_2115c' (errno: 121)


Based on previous error codes, I was assuming this was a FK naming collision. So, I executed this query to find out where is the other FK



SELECT constraint_name, table_name
FROM information_schema.table_constraints
WHERE constraint_type = 'FOREIGN KEY' AND table_schema = DATABASE()
ORDER BY constraint_name;


To my "surprise" there is no other FK with that name. Believe me, I checked a lot of times. Have no idea. If I execute the query with a different FK name, it runs perfectly.





Aucun commentaire:

Enregistrer un commentaire