我有一个关于外键的问题。
当我想将外键添加到我创建的第二个表的主键的第一个表中时,它是如何工作的?
CREATE TABLE table1
(
name_id INT NOT NULL,
team TEXT REFERENCES table2(team_id),
PRIMARY KEY(name_id)
);
CREATE TABLE table2
(
team_id INT NOT NULL,
teamname TEXT,
PRIMARY KEY(team_id)
);
如果我尝试上面的代码,我会收到以下错误:
错误:关系“”不存在
提前致谢。
要么先创建第二个表。或使用alter table
. 也就是说,创建没有引用的第一个表,然后执行:
alter table table1 add constraint fk_table1_team
foreign key (team_id) REFERENCES table2(team_id);
声明为table1
:
CREATE TABLE table1 (
name_id INT NOT NULL,
team_id INT,
PRIMARY KEY(name_id)
);
如果整数可用,表之间的引用应该在主键上,当然不是在字符列上。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句