我有两个表:发票和发票项目。我需要两者之间建立一对多关系并进行级联删除(因此,如果发票被删除,项目也会被删除)。
发票上的主键跨越两列:invoice_number、vendor_number
invoice_items 上的主键跨越三列:invoice_number、vendor_number、item_number
如何使用invoice_number 和vendor_number 列向invoice_items 表添加外键约束?
我尝试了这个,但没有成功:
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.
最佳答案
使用显示innodb状态
。这将转储一大块文本。中间某处是“最后一个外键错误”。它将包含有关更改表失败原因的更多详细信息。
一种可能性是字段类型不匹配。两个表中的键控字段必须完全相同。您无法将带符号的字段链接到无符号的字段,或者将 int 链接到 bigint 等...
关于mysql - 在 MySQL innodb 中创建具有多个字段的外键约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6603149/