Question

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

No correct solution

OTHER TIPS

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:

  1. 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.

  2. 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.

  3. 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top