MySQL错误:150

时间:2012-03-21 08:24:43

标签: mysql

我有一张看起来像这样的表:

CREATE TABLE `countrytable` (
  `countryCode` varchar(2) NOT NULL DEFAULT '',
  `currencyCode` varchar(3) NOT NULL,
  `currencySymbol` varchar(4) NOT NULL DEFAULT '',
  `currencyIsRight` tinyint(4) DEFAULT '0',
  `currencyName` varchar(45) DEFAULT 'US Dollar',
  `countryName` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`countryCode`,`currencyCode`),
  UNIQUE KEY `countryCode_UNIQUE` (`countryCode`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

我正在尝试创建另一个表,该表在countrytable.currencyCode上有一个外键。我一直收到以下错误:

The specified relation was unable to be created.
MySQL said: Can't create table 'noteitdb.#sql-b8_13' (errno: 150)

两列的数据类型完全匹配。我能错过什么?

4 个答案:

答案 0 :(得分:1)

ALTER TABLE `countrytable`   
  DROP PRIMARY KEY,
  ADD PRIMARY KEY (`currencyCode`, `countryCode`);

应首先将currencyCode编入索引。请参阅MySQL docs

答案 1 :(得分:1)

如果您想要引用CurrencyCode的外键约束,那么此表中此列需要UNIQUE(或主键)约束:

ALTER TABLE countrytable   
  ADD UNIQUE KEY (currencyCode);

答案 2 :(得分:0)

从PK列中删除unsigned

答案 3 :(得分:0)

execute below line before creating/altering table table :

 SET FOREIGN_KEY_CHECKS = 0;
 // all your sql craete ,alter  etc goes here  and then below 
 SET FOREIGN_KEY_CHECKS = 1;

FOREIGN_KEY_CHECKS option specifies whether or not to check foreign key constraints for InnoDB tables. 
-- Specify to check foreign key constraints (this is the default)
SET FOREIGN_KEY_CHECKS = 1;
 
-- Do not check foreign key constraints
SET FOREIGN_KEY_CHECKS = 0;
When to Use : Temporarily disabling referential constraints (set FOREIGN_KEY_CHECKS to 0) is useful when you need to re-create the tables and load data in any parent-child order