如何解决创建唯一索引时“外键约束形成不正确”
我试图执行以下查询:
CREATE TABLE `lob_sections` (
`id` int(11) NOT NULL AUTO_INCREMENT,`section_name` varchar(600) NOT NULL,`lob_type` varchar(64) NOT NULL,`agency_id` varchar(64) NOT NULL,`display_order` tinyint(2) NOT NULL DEFAULT 1,`active` tinyint(1) NOT NULL DEFAULT 1,`created_date` timestamp NOT NULL DEFAULT current_timestamp(),`last_modified_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),PRIMARY KEY (`id`),UNIQUE KEY `unq_lob_sections` (`agency_id`,`lob_type`,`section_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `lob_custom_fields` (
`id` int(11) NOT NULL AUTO_INCREMENT,`section_id` int(11) NOT NULL,`field_label` varchar(1400) NOT NULL,`field_type` varchar(20) NOT NULL,`display_order` tinyint(3) NOT NULL DEFAULT 1,`required` tinyint(1) NOT NULL DEFAULT 0,CONSTRAINT unq_section_field_label UNIQUE (section_id,field_label),CONSTRAINT `fk_section_id` FOREIGN KEY (`section_id`) REFERENCES `lob_sections` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
lob_sections 表已成功创建,但 lob_custom_fields 未创建,它抛出以下错误:
#1005 - 无法创建表 abc_db
.lob_custom_fields
(错误号:150“外键约束的格式不正确”)(详细信息...)
当我点击详细信息时,它会显示原因“Create table
abc_db.
lob_custom_fieldswith foreign key
fk_section_id constraint Failed. There is no index in the referenced table where the referenced columns appear as the first columns.------------
”。
如果我从 lob_custom_fields 表的 create table 语句中删除“CONSTRAINT unq_section_field_label UNIQUE (section_id,
”行,则它创建成功。
如何在 lob_custom_fields 表中添加唯一索引?当我尝试添加唯一索引时,Create-Alter 都显示相同的错误。任何帮助将不胜感激。
解决方法
错误信息说
指定的键太长;最大密钥长度为 3072 字节
InnoDB 内部最大密钥长度为 3500 字节,但 MySQL 本身将其限制为 3072 字节。此限制适用于多列索引中组合索引键的长度。
这是用于 mysql 8
所以你必须定义
field_label
varchar(1022)
适合
CREATE TABLE `lob_sections` (
`id` int(11) NOT NULL AUTO_INCREMENT,`section_name` varchar(600) NOT NULL,`lob_type` varchar(64) NOT NULL,`agency_id` varchar(64) NOT NULL,`display_order` tinyint(2) NOT NULL DEFAULT 1,`active` tinyint(1) NOT NULL DEFAULT 1,`created_date` timestamp NOT NULL DEFAULT current_timestamp(),`last_modified_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),PRIMARY KEY (`id`),UNIQUE KEY `unq_lob_sections` (`agency_id`,`lob_type`,`section_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `lob_custom_fields` (
`id` int(11) NOT NULL AUTO_INCREMENT,`section_id` int(11) NOT NULL,`field_label` varchar(1022) NOT NULL,`field_type` varchar(20) NOT NULL,`display_order` tinyint(3) NOT NULL DEFAULT 1,`required` tinyint(1) NOT NULL DEFAULT 0,CONSTRAINT unq_section_field_label UNIQUE (section_id,field_label),CONSTRAINT `fk_section_id` FOREIGN KEY (`section_id`) REFERENCES `lob_sections` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
dbfiddle here
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。