PostgreSQL:外键约束中的列引用不存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16987538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 00:57:12  来源:igfitidea点击:

PostgreSQL: Column Reference in Foreign Key Constraint Does Not Exist

sqlpostgresqlforeign-keyspostgresql-9.2

提问by caleb

I'm still new to postgreSQL. I have two tables I created that I want to go back and add Primary and Foreign key constraints for and no matter what I do I can't seem to add a foreign key. Here's what I have:

我还是 postgreSQL 的新手。我创建了两个表,我想返回并为其添加主键和外键约束,无论我做什么,我似乎都无法添加外键。这是我所拥有的:

Two Tables:

两个表:

test=# \d statename
      Table "public.statename"
 Column |     Type      | Modifiers
--------+---------------+-----------
 code   | character(2)  | not null
 name   | character(30) |
Indexes:
    "statename_pkey" PRIMARY KEY, btree (code)

test=# \d customer
          Table "public.customer"   
    Column   |     Type      | Modifiers
-------------+---------------+-----------
 customer_id | integer       |
 name        | character(30) |
 telephone   | character(20) |
 city        | character(25) |
 street      | character(40) |
 state       | character(2)  |
 zipcode     | character(10) |
 country     | character(20) |

Here's the command I'm running:

这是我正在运行的命令:

test=# ALTER TABLE customer ADD CONSTRAINT
state FOREIGN KEY (code) REFERENCES
statename (code) >MATCH FULL;

Here's the error I'm getting:

这是我得到的错误:

ERROR:  column "code" referenced in foreign key constraint does not exist

I'm looking at the column! I know it exists! Please help a brother out!

我在看专栏!我知道它存在!请兄弟们帮帮忙!

采纳答案by Derek Kromm

Code does not exist in your customer table. It's state.

您的客户表中不存在代码。是状态。

ALTER TABLE customer 
ADD CONSTRAINT state FOREIGN KEY (state) 
REFERENCES statename (code) >MATCH FULL;