MySQL:错误消息无法创建表(错误号:150)

时间:2012-02-27 05:46:47

标签: mysql sql mysql-error-1005

我有两张桌子,'po'和'receive'

CREATE TABLE `po` (
  `PO_ID` bigint(20) NOT NULL,
  `SERVICE_TYPE` bit(1) DEFAULT NULL,
  `ENTRY_DATE` date NOT NULL,
  `RECEIPT_DATE` date DEFAULT NULL,
  `TURNOVER` date DEFAULT NULL,
  `MOBILIZATION` date DEFAULT NULL,
  `SITE_NAME` varchar(255) NOT NULL,
  `SITE_CODE` varchar(45) DEFAULT NULL,
  `SITE_TIN` varchar(45) DEFAULT NULL,
  `SITE_ADDRESS` varchar(255) NOT NULL,
  `COST` decimal(11,2) NOT NULL,
  `XML` text,
  PRIMARY KEY (`PO_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$

CREATE TABLE `receive` (
  `RECEIPT_ID` varchar(100) NOT NULL,
  `RECEIPT_DATE` date NOT NULL,
  `PO_NUMBER` bigint(20) NOT NULL,
  `SUPPLIER_ID` int(11) NOT NULL,
  PRIMARY KEY (`RECEIPT_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$

我试图通过在'receive'表上定义外键'fk_po'来连接两个表

ALTER TABLE `fourthwave`.`receive` 
  ADD CONSTRAINT `fk_po`
  FOREIGN KEY (`PO_NUMBER` )
  REFERENCES `fourthwave`.`po` (`PO_ID` )
  ON DELETE SET NULL
  ON UPDATE SET NULL
, ADD INDEX `fk_po` (`PO_NUMBER` ASC)

但是,上面的alter query会引发错误:

Error Code: 1005. Can't create table 'fourthwave.#sql-aec_11' (errno:150)

我收到此错误是因为两个表上的字段名称,'PO_ID'和'PO_NUMBER'不同?

2 个答案:

答案 0 :(得分:3)

在ALTER TABLE之后执行SHOW ENGINE INNODB STATUS语句,你会看到错误信息 - '你已经定义了一个SET NULL条件,虽然有些 列被定义为NOT NULL'。

ALTER TABLE `receive` 
  ADD CONSTRAINT `fk_po`
  FOREIGN KEY (`PO_NUMBER` )
  REFERENCES `po` (`PO_ID` )
  ON DELETE SET NULL
  ON UPDATE SET NULL
 , ADD INDEX `fk_po` (`PO_NUMBER` ASC);

SHOW ENGINE INNODB STATUS;

答案 1 :(得分:0)

您需要PO_NUMBER表中receive的索引。您在外键中引用的字段始终应编入索引。