[英]creating a table using foreign key of another table error
I have the table uc_users with the following columns: 我的表uc_users包含以下列:
| id | user_name | display_name | password | email |
I want to create a second table uc_user_network using the foreign key user_name from the uc_users table. 我想使用uc_users表中的外键user_name创建第二个表uc_user_network。
Here is my attempt: 这是我的尝试:
CREATE TABLE uc_user_network
(
ID int NOT NULL AUTO_INCREMENT,
GraphName varchar(255) NOT NULL,
user_name varchar(50),
networkid varchar(255),
PRIMARY KEY (ID)
FOREIGN KEY (user_name) REFERENCES uc_users(user_name)
)
ALTER TABLE uc_users
ADD CONSTRAINT fk_users
FOREIGN KEY (user_name)
REFERENCES uc_user_network(ID)
However, I get the following error: 但是,出现以下错误:
FOREIGN KEY (user_name) REFERENCES uc_users(user_name)
Any help would be appreciated. 任何帮助,将不胜感激。 Thanks 谢谢
Your user_name
in uc_user_network
should be the same type as user_name
in uc_users
the same as ID
in uc_user_network
. 你user_name
在uc_user_network
应该是同一类型user_name
在uc_users
一样的ID
在uc_user_network
。 So what type should it be? 那应该是什么类型呢? int
or varchar(255)
? int
或varchar(255)
?
FOREIGN KEY (user_name) REFERENCES uc_users(user_name)
is not an error: What is the actual error you're getting? FOREIGN KEY (user_name) REFERENCES uc_users(user_name)
不是错误:您得到的实际错误是什么?
You won't be able to create a foreign key unless the following conditions are met: 除非满足以下条件,否则您将无法创建外键:
The dependency must already exist. 依赖项必须已经存在。 In your case, if the table uc_users
does not yet exist, you can't define a foreign key referring to it. 在您的情况下,如果表uc_users
还不存在,则无法定义引用该表的外键。
The referenced column(s) must comprise a primary key
(or, depending on whether or not your SQL implementation supports it, an alternate key such as a unique index
). 被引用的列必须包含一个primary key
(或者,取决于您的SQL实现是否支持它,一个替代键,例如unique index
)。 In your case, if the column user_name
in the table uc_users
is not a primary key, you can't reference it as such. 在您的情况下,如果uc_users
表中的user_name
列不是主键,则不能这样引用它。
Further, if the foreign reference is to a composite key , composed of multiple columns, all the key columns must be referenced, in the same order in which they are defined in the primary key. 此外,如果外部引用是由多个列组成的复合键 ,则必须按在主键中定义的顺序来引用所有键列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.