修改表添加外键

时间:2014-02-26 23:30:03

标签: sql foreign-keys

我的表格users包含以下列:

| id | user_name | display_name | password | email |

我需要使用uc_user_network表中的外键user_name创建第二个表users

| id | graphname | networkid | user_name | 

这是我的尝试:

CREATE TABLE uc_user_network
(
   ID int NOT NULL AUTO_INCREMENT,
   GraphName varchar(255) NOT NULL,
   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(user_name)

有人能告诉我哪里出错了吗?感谢

1 个答案:

答案 0 :(得分:1)

CREATE TABLE uc_user_network
(
ID int NOT NULL IDENTITY(1,1),   --<-- Auto Increment is Identity 
GraphName varchar(255) NOT NULL,
user_name [DataType],     --<-- you need to create this column in this table 1st
networkid varchar(255),
PRIMARY KEY (ID)
FOREIGN KEY (user_name) REFERENCES users(user_name) --<-- Column Name in Users Table.
)                ^                   ^
     Column name in this table        This is the tablename

引用列必须是Referenced表中的主键。此表中User_Name的DataType也应与Users Table中User_Name的数据类型匹配。