【问题标题】:Column <tablename>_id referenced in foreign key not found未找到外键引用的列 <tablename>_id
【发布时间】:2014-01-17 02:28:59
【问题描述】:

我将在 7 周内浏览 7 个数据库。

在 PostgreSQL 中,我创建了一个具有 SERIAL 场地 ID 列的场地表。

\d venues的输出

                                        Table "public.venues"
     Column     |          Type          |                         Modifiers
----------------+------------------------+-----------------------------------------------------------
 venue_id       | integer                | not null default nextval('venues_venue_id_seq'::regclass)
 name           | character varying(255) |
 street_address | text                   |
 type           | character(7)           | default 'public'::bpchar
 postal_code    | character varying(9)   |
 country_code   | character(2)           |
Indexes:
    "venues_pkey" PRIMARY KEY, btree (venue_id)
Check constraints:
    "venues_type_check" CHECK (type = ANY (ARRAY['public'::bpchar, 'private'::bpchar]))
Foreign-key constraints:
    "venues_country_code_fkey" FOREIGN KEY (country_code, postal_code) REFERENCES cities(country_code, postal_code) MATCH FULL

下一步是创建一个使用外键引用venue_id 的事件表。

我正在尝试这个:

CREATE TABLE events (
event_id SERIAL PRIMARY KEY,
title text,
starts timestamp,
ends timestamp,
FOREIGN KEY (venue_id) REFERENCES venues (venue_id));

我得到这个错误:

ERROR: column "venue_id" referenced in forgein key not found

怎么了?

【问题讨论】:

  • 显示\d venues 的输出。表存在吗?它有一个名为venue_id 的列吗?
  • 存在,它有一个venue_id列作为主键。我现在不在那台机器上,所以我明天会跟进。
  • 添加到原帖
  • 我能够使用venue_id 整数REFERENCES 场地创建它。测试..
  • 也许这条评论来得太晚了,但我发现有一个很好的答案来创建序列类型外键,stackoverflow.com/a/28560619/2191173

标签: postgresql


【解决方案1】:

您还需要初始化外键列。看这里http://www.postgresql.org/docs/current/static/ddl-constraints.html#DDL-CONSTRAINTS-FK @mu 的来源和来源太短了

【讨论】:

  • 我不明白。是我缺少类型(int)吗? \n 就像他们的例子:P_Id int FOREIGN KEY REFERENCES Persons(P_Id)
【解决方案2】:

我正在阅读本书的第二版,所以情况可能略有变化。

要创建表,您必须明确将venues_id 声明为表中的一列,就像您的其他列一样:

CREATE TABLE events (
    event_id SERIAL PRIMARY KEY,
    title text,
    starts timestamp,
    ends timestamp,
    venue_id integer,  -- this is the line you're missing!
    FOREIGN KEY (venue_id)
        REFERENCES venues (venue_id) MATCH FULL
    );

一旦你执行了,表就被创建了:

7dbs=# \dt
           List of relations
 Schema |   Name    | Type  |  Owner
--------+-----------+-------+----------
 public | cities    | table | postgres
 public | countries | table | postgres
 public | events    | table | postgres
 public | venues    | table | postgres

【讨论】:

    猜你喜欢
    • 2020-11-25
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    • 2018-10-29
    • 2019-04-18
    • 2010-10-13
    • 1970-01-01
    • 2011-01-29
    相关资源
    最近更新 更多