在person_addresses
表中,我得到错误Foreign key constraint is incorrectly formed
。我的版本是10.4.24-MariaDB
CREATE TABLE persons (
person_id int(11) NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
email varchar(50) DEFAULT NULL,
phone int(11) DEFAULT NULL,
bio text DEFAULT NULL,
dob date DEFAULT NULL,
gender enum('Male','Female','Other') NOT NULL,
status tinyint(4) NOT NULL,
created_at timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (person_id),
UNIQUE KEY email (email),
UNIQUE KEY phone (phone)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE person_addresses (
person_id int(11) NOT NULL ,
address text NOT NULL,
created_at timestamp NOT NULL DEFAULT current_timestamp(),
UNIQUE KEY uc_person_address (person_id,address),
CONSTRAINT fk_person FOREIGN KEY (person_id) REFERENCES persons(person_id) ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
更详细的错误
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2023-01-11 12:41:52 0x421c Error in foreign key constraint of table `test`.`person_addresses`:
There is no index in table ```test``.``person_addresses``` where the columns appear
as the first columns. Constraint:
FOREIGN KEY (person_id) REFERENCES persons (person_id) ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
Please refer to https://mariadb.com/kb/en/library/foreign-keys/ for correct foreign key definition.Create table `test`.`person_addresses` with foreign key constraint failed. There is no index in the referenced table where the referenced columns appear as the first columns near ' FOREIGN KEY (person_id) REFERENCES persons (person_id) ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4'.
1条答案
按热度按时间a5g8bdjr1#
我想我在MariaDB中找到了匹配的bug报告:https://jira.mariadb.org/browse/MDEV-29717
问题在于,如果外键所需的索引非常大,则会自动创建索引,但如果该索引大于存储引擎的索引大小限制,则会失败(在您使用的MariaDB版本中应该是3072字节,因为它默认为具有innodb_large_prefix=on的DYNAMIC行格式)。索引中的
text
类型太大,无法在不定义索引前缀的情况下建立索引。但是外键不能使用用索引前缀定义的索引。不幸的是,由于外键是在存储引擎的深处实现的,因此很少有机会显示更具信息性的错误消息。这是可插入存储引擎实现的一个问题。
在您的情况下,解决方案应该是更改
address
列类型。它不能是text
,只能是长度不超过索引前缀长度限制的varchar
。例如,我用MariaDB 10.4. https://dbfiddle.uk/5jTX8iFt进行了测试,如果
address
是text
,则会失败,如果address
是varchar(255)
,则工作正常。我怀疑你无论如何都需要
text
作为地址。有人有需要64KB的地址吗?