I have the table uc_users with the following columns:
| 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.
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
. So what type should it be? int
or varchar(255)
?
FOREIGN KEY (user_name) REFERENCES uc_users(user_name)
is not an error: What is the actual error you're getting?
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.
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
). 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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.