第一个表中的外键 [英] Foreign key in the first table

查看:104
本文介绍了第一个表中的外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对外键有疑问。

当我要将外键添加到我对主表进行引用的第一个表中时,它如何工作?我创建的第二个表的键?

How does it work when I want to add a foreign key to the first table that I make that references to the primary key of the second table I create?

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)
);

如果我尝试上面的代码,则会出现以下错误:

If I try the code above I get the following error:


错误:关系不存在

ERROR: relation "" does not exist

请先感谢。

推荐答案

要么首先创建第二个表。或使用更改表。也就是说,创建第一个没有引用的表,然后执行以下操作:

Either create the second table first. Or use alter table. That is, create the first table without the reference and then do:

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)
);

表之间的引用应该在主键上,当然也不能在字符列上整数可用。

The reference between the tables should be on the primary key and certainly not on a character column, if an integer is available.

这篇关于第一个表中的外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆