简体   繁体   English

MySQL添加外键

[英]MySQL add Foreign Key

I want to update a column which is currently a plain INT(16) so that it references a FK on another table. 我想更新当前为普通INT(16)的列,以便它引用另一个表上的FK。 I've tried the following, but with errors: 我尝试了以下操作,但有错误:

ALTER TABLE ts_keys ADD CONSTRAINT FK_account_id FOREIGN KEY (account_id) REFERENCES accounts(id) ON UPDATE CASCADE ON DELETE CASCADE

EDIT: Sorry, forgot to add the error: 编辑:对不起,忘记添加错误:

Can't create table (errno: 150)

Both tables are Innodb. 这两个表都是Innodb。

EDIT 2: I also tried re-creating the table but same error: 编辑2:我也尝试重新创建表,但相同的错误:

    CREATE TABLE ts_keys (
  id int PRIMARY KEY AUTO_INCREMENT,
  account_id int,
  FOREIGN KEY fk_account_id1(account_id) REFERENCES accounts(id)
) ENGINE=InnoDB;

The datatype of the foreign key column must match EXACTLY the datatype of the referenced column. 外键列的数据类型必须与引用列的数据类型完全匹配。

Do a SHOW CREATE TABLE accounts and look at the definition of the id column. 做一个SHOW CREATE TABLE accounts并查看id列的定义。

Whatever that column is defined as INT UNSIGNED , BIGINT , VARCHAR(16) , whatever, 将该列定义为INT UNSIGNEDBIGINTVARCHAR(16)任何内容,

the column you want to define as a foreign key (the account_id column in ts_keys table) must match that datatype EXACTLY . 要定义为外键的列( ts_keys表中的account_id列)必须与该数据类型EXACTLY相匹配。 (It's just the datatype that has to match. The column comment doesn't have to match, the DEFAULT value doesn't have to match, the NULL/NOT NULL doesn't have to match. But it's required that the datatypes match. (这只是必须匹配的数据类型。列注释不必匹配,DEFAULT值不必匹配,NULL / NOT NULL不必匹配。但是需要数据类型匹配。


Your syntax for adding the constraint looks correct: 您添加约束的语法看起来正确:

ALTER TABLE ts_keys
  ADD CONSTRAINT FK_account_id 
  FOREIGN KEY (account_id) 
  REFERENCES accounts(id) 
  ON UPDATE CASCADE ON DELETE CASCADE

Admittedly, the "Can't create table (errno: 150)" has to be the least helpful message regarding what's actually causing the problem. 不可否认,“无法创建表(errno:150)”必须是关于实际上是什么引起问题的最没有帮助的消息。 (At least the error isn't the "check the manual" syntax error. (至少该错误不是“检查手册”语法错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM