10.4.24-MariaDB -外键约束格式不正确

pxyaymoc  于 2023-01-13  发布在  其他
关注(0)|答案(1)|浏览(151)

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'.
a5g8bdjr

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进行了测试,如果addresstext,则会失败,如果addressvarchar(255),则工作正常。
我怀疑你无论如何都需要text作为地址。有人有需要64KB的地址吗?

相关问题