简体   繁体   English

外键无法添加

[英]Foreign Key Unable to Add

I am try to add foreign key 我尝试添加外键

CREATE TABLE `uniform_product_details` ( 
  `upc_id` VARCHAR(32) NOT NULL, 
  `product_id` int(11),
  `condition_id` tinyint(1) NOT NULL,
  `status`  INT NOT NULL,
  `created_by` VARCHAR(32), 
  `updated_by` VARCHAR(32),
  `date_added` datetime NOT NULL,
  `date_modified` datetime NOT NULL,
  PRIMARY KEY(`upc_id`),
  INDEX `pid` (`product_id`),
  FOREIGN KEY(`product_id`) REFERENCES product(`product_id`) ON DELETE CASCADE
);

but my Toad showing an error while doing this 但是我的蟾蜍在执行此操作时显示错误

MySQL Database Error: Cannot add foreign key constraint MySQL数据库错误:无法添加外键约束

Is there any logical mistake I am caring with this Query. 我对此查询有任何逻辑上的错误吗? Help !! 救命 !!

Try following code: 尝试以下代码:

CREATE TABLE `uniform_product_details1` ( 
  `upc_id` VARCHAR(32) NOT NULL, 
  `product_id` int(11),
  `condition_id` tinyint(1) NOT NULL,
  `status`  INT NOT NULL,
  `created_by` VARCHAR(32), 
  `updated_by` VARCHAR(32),
  `date_added` datetime NOT NULL,
  `date_modified` datetime NOT NULL,
  PRIMARY KEY(`upc_id`),
  INDEX `pid` (`product_id`),
  FOREIGN KEY(`product_id`)  REFERENCES product(`product_id`) ON DELETE CASCADE
)ENGINE=InnoDB;

Maybe it has to do with the Engine... MyISAM tables do not support foreign keys. 可能与引擎有关... MyISAM表不支持外键。 Define the engine as InnoDB: 将引擎定义为InnoDB:

create table uniform_product_details(
    -- All your column definitions
)ENGINE=InnoDB;

You may need to change the engine for other tables. 您可能需要更改其他表的引擎。 If that's the case, use this: 如果是这样,请使用以下命令:

alter table another_table ENGINE=InnoDB;

The full sequence of the solution might be as follows: 解决方案的完整顺序如下:

  1. Create the tables without foreign key definitions 创建没有外键定义的表
  2. Alter all your tables: Set the engine to InnoDB for all of them 更改所有表:将所有表的引擎设置为InnoDB
  3. Add the foreign key definitions with: 使用以下命令添加外键定义:

    alter table any_table add foreign key ... ; alter table any_table add foreign key ... ;


Further reference about MySQL Storage Engines: 有关MySQL存储引擎的更多参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM