错误信息:
SQLSTATE[42000]: Syntax error or access violation: 1239 Incorrect foreign key definition for 'fk.faq.product_id': Key reference and table reference don't match
产品表:
CREATE TABLE `product` ( `id` BINARY(16) NOT NULL, `version_id` BINARY(16) NOT NULL, `created_at` DATETIME(3) NOT NULL, `updated_at` DATETIME(3) NULL, PRIMARY KEY (`id`,`version_id`), ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
常见问题表:
CREATE TABLE `faq` ( `id` BINARY(16) NOT NULL, `question` VARCHAR(255) NULL, `answer` VARCHAR(255) NULL, `product_id` BINARY(16) NOT NULL, `created_at` DATETIME(3) NOT NULL, `updated_at` DATETIME(3) NULL, PRIMARY KEY (`id`), KEY `fk.faq.product_id` (`product_id`), CONSTRAINT `fk.faq.product_id` FOREIGN KEY (`product_id`) REFERENCES `product` (`id`,`version_id`) ON DELETE SET NULL ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
我创建了一个常见问题表,与产品表结合在一起,但是它总是出现错误,我找不到表中的问题在哪里出错了。谢谢帮助。
移除这段英文中的逗号 - PRIMARY KEY (id, version_id),移除 product_id BINARY(16) 中的 not null,移除 version_id。 REFERENCES
product
(id
,version_id
)https://dbfiddle.uk/rg25idw-
在引用的表中,必须存在一个索引,其中引用的列是以相同顺序作为第一列的。
https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html