SQL外部密钥错误(ERRNO:150'外键约束是错误形成的“)
嗨,我有这三个非常简单的桌子,但是我无法修复它以获取正确的外键格式。
创建餐桌公司( company_name varchar(30)唯一不为空, bid int(15)不是独一无二的, cid int(15)不是独一无二的, 外键(BID)参考分支(branch_id), 外键(CID)参考联系人(Contact_ID) );
创建表分支( branch_id int(15)不是null auto_increment独特, branch_type varchar(30), cid int(15)不是独一无二的, 主键(branch_id), 外键(CID)参考联系人(Contact_ID) );
创建表联系( contact_id int(15)不是null auto_increment独特, fst_name varchar(20), mdl_name varchar(20), lst_name varchar(20), 性varchar(20), DOB日期, phone_number int(15), 地址VARCHAR(255), 电子邮件varchar(255), bid int(15)不是独一无二的, 主键(contact_id), 外键(BID)参考分支(branch_id) )引擎= innodb;
这三个都有相同的错误150。 非常感谢您的帮助。
Hi I have this three very simple tables but I can't fix it to get the right format of foreign key.
CREATE TABLE company(
company_name varchar(30) UNIQUE NOT NULL,
bid INT(15) NOT NULL UNIQUE,
cid INT(15) NOT NULL UNIQUE,
FOREIGN KEY (bid) REFERENCES branch(branch_id),
FOREIGN KEY (cid) REFERENCES contact(contact_id)
);
CREATE TABLE branch(
branch_id INT(15) NOT NULL AUTO_INCREMENT UNIQUE,
branch_type varchar(30),
cid INT(15) NOT NULL UNIQUE,
PRIMARY KEY (branch_id),
FOREIGN KEY (cid) REFERENCES contact(contact_id)
);
CREATE TABLE contact(
contact_id INT(15) NOT NULL AUTO_INCREMENT UNIQUE,
fst_name varchar(20),
mdl_name varchar(20),
lst_name varchar(20),
sex varchar(20),
dob DATE,
phone_number INT(15),
address varchar(255),
email varchar(255),
bid INT(15) NOT NULL UNIQUE,
PRIMARY KEY (contact_id),
FOREIGN KEY (bid) REFERENCES branch (branch_id)
)ENGINE=InnoDB;
All three of them have the same error150.
Thank you so much for helping.table
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题在于,您将
Company
表参考分支
和Contact
表创建之前。另外,分支表引用联系人表,反之亦然,因此数据库是这样的:
创建
联系人
表...有一个bid
字段连接到名称的表分支
...表分支不存在 - >错误您必须首先创建
联系人
表,但是 没有外国ID参考bid ,然后创建branch
表然后公司
表。拥有桌子后,您可以执行另一个查询以添加外国ID引用到投标。
因此,
请注意我删除了
外键(BID)参考分支(branch_id)
然后:
ps以相同的顺序运行命令
The problem is that you have the
company
table reference thebranch
andcontact
table before they are created.Also, the branch table references the contact table and vice versa so the database goes like that:
Creating the
contact
table ... there is abid
field connected to a table namedbranch
... table branch does not exist -> errorYou have to create the
contact
table first but without the foreign id reference to bid, then createbranch
table and thencompany
table.After you have your tables all set you can execute another query to add a foreign id reference to bid.
So Like this:
Notice I removed
FOREIGN KEY (bid) REFERENCES branch (branch_id)
And then:
P.S Run the commands in the same order