2

I'm going through 7 Databases in 7 Weeks.

In PostgreSQL, I created a venues table that has a SERIAL venue_id column.

output of \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

The next step is to create an event table that references venue_id with a foreign key.

I'm trying this:

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

And I get this error:

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

What's wrong?

AllanLRH
  • 1,124
  • 1
  • 12
  • 23
quantumpotato
  • 9,637
  • 14
  • 70
  • 146

2 Answers2

1

you need to initialize the foreign key column too. see here http://www.postgresql.org/docs/current/static/ddl-constraints.html#DDL-CONSTRAINTS-FK source & credit from @mu is too short

Meow
  • 138
  • 1
  • 7
  • I don't undesrtand. Is it that I'm missing the type (int)? \n like in their example: P_Id int FOREIGN KEY REFERENCES Persons(P_Id) – quantumpotato Jan 17 '14 at 02:35
0

I'm going through the second edition of this book, so things might have changed slightly.

To create the table, you explicitly have to declare the venues_id as a column in your table, just like the rest of your columns:

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

Once you have executed that, the table is created:

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
AllanLRH
  • 1,124
  • 1
  • 12
  • 23