在MySQL innodb中创建具有多个字段的外键约束

时间:2011-07-06 21:20:39

标签: mysql sql foreign-keys innodb

我有两张桌子:发票& invoice_items。我需要两者之间的一对多关系与级联删除(所以如果发票被删除,项目也会被删除)。

发票上的主键跨越两列:invoice_number,vendor_number

invoice_items上的主键跨越三列:invoice_number,vendor_number,item_number

如何使用invoice_number& amp;来为invoice_items表添加外键约束? vendor_number列?

我尝试过这个并没有用:

ALTER TABLE `invoice_items`
ADD FOREIGN KEY (`invoice_number`,`vendor_number`)
REFERENCES `invoices`(`invoice_number`,`vendor_number`) ON DELETE CASCADE;

ERROR 1005 (HY000): Can't create table 'test_db.#sql-12c8_db1ad' (errno: 150)

以下是表格定义:

CREATE TABLE IF NOT EXISTS `invoices` (
  `vendor_number` varchar(20) NOT NULL,
  `invoice_number` varchar(20) NOT NULL,
  `po_number` varchar(50) NOT NULL,
  `inbound_message_id` int(11) NOT NULL,
  `created_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`vendor_number`,`invoice_number`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `invoice_items` (
  `vendor_number` varchar(20) NOT NULL,
  `invoice_number` varchar(20) NOT NULL,
  `po_item_number` varchar(6) NOT NULL,
  `quantity` float NOT NULL,
  `amount` decimal(10,2) NOT NULL COMMENT 'Total amount invoiced for this line item',
  PRIMARY KEY (`vendor_number`,`invoice_number`,`po_item_number`),
  KEY `invoice_key` (`vendor_number`,`invoice_number`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

以下是show innodb status的输出:

110707 12:26:19 Error in foreign key constraint of table test_db/#sql-12c8_dcbfb:
FOREIGN KEY (`invoice_number`,`vendor_number`)
REFERENCES `invoices`(`invoice_number`,`vendor_number`) ON DELETE CASCADE:
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html
for correct foreign key definition.

1 个答案:

答案 0 :(得分:5)

使用show innodb status。这将丢弃一大块文本。中间某处是“最后一个外键错误”。它将包含更多有关alter table失败原因的详细信息。

一种可能性是字段类型不匹配。两个表中的键控字段必须完全相同。您不能将签名字段链接到无符号字段,或将int链接到bigint等...