gpt4 book ai didi

mysql - 外键错误

转载 作者:行者123 更新时间:2023-11-29 13:38:28 26 4
gpt4 key购买 nike

为什么外键让我头疼?
首先,我创建了数据库名称colorcode,然后创建了paper表,该表工作正常:

CREATE TABLE paper (
paper_id int(20) NOT NULL,
description VARCHAR(40) NOT NULL,
paper_color VARCHAR(40) NOT NULL,
PRIMARY KEY (paper_id, paper_color)
) ENGINE=InnoDB;

然后

CREATE TABLE brick(
brick_id int(20) NOT NULL,
description varchar(40) NOT NULL,
brick_color varchar (40) NOT NULL,
PRIMARY KEY (brick_id),
FOREIGN KEY (brick_color) REFERENCES paper(paper_color)
) ENGINE=InnoDB;

这不是=>

#1005 - 无法创建表“colorcode.brick”(错误号:150)

感谢您的帮助

最佳答案

create table paper (
paper_id int(20) not null,
description VARCHAR(40)not null,
paper_color VARCHAR(40) NOT NULL,
primary key (paper_id, paper_color),
INDEX(`paper_color`)
)engine=InnoDB;

create table brick (
brick_id int(20) not null,
description varchar(40) not null,
brick_color varchar (40) not null,
primary key (brick_id),

CONSTRAINT foreign key (`brick_color`) REFERENCES paper(`paper_color`)
)engine=InnoDB;

演示:http://sqlfiddle.com/#!2/316d9

InnoDB permits a foreign key to reference any index column or group of columns. However, in the referenced table, there must be an index where the referenced columns are listed as the first columns in the same order.

http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html

“paper_color”必须是索引才能引用。

希望这有帮助。

关于mysql - 外键错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18450621/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com