简体   繁体   中英

PostgresQL Foreign Key Syntax Error

When attempting to create the second table in this respective database, I'm getting the following error message:

ERROR:  syntax error at or near "REFERENCES"
LINE 3: master_directory REFERENCES auth_table (directory),

Here's the database structure that I attempted to create:

CREATE TABLE auth_table (
id SERIAL PRIMARY KEY,
directory VARCHAR,
image VARCHAR
)

CREATE TABLE master_table (
id SERIAL PRIMARY KEY,
master_directory references auth_table (directory),
master_image references auth_table (image)
)

Any reason why I'm receiving that error? Any help would be appreciated!

You've left the data type off, but that syntax error is the least of your problems.

Your foreign key references need to refer to unique column(s). So "auth_table" probably needs to be declared one of these ways. (And you probably want the second one, if your table has something to do with the paths to files.)

CREATE TABLE auth_table (
  id SERIAL PRIMARY KEY,
  directory VARCHAR not null unique,
  image VARCHAR not null unique
);

CREATE TABLE auth_table (
  id SERIAL PRIMARY KEY,
  directory VARCHAR not null,
  image VARCHAR not null,
  unique (directory, image)
);

Those unique constraints mean quite different things, and each requires a different foreign key reference. Assuming that you want to declare "auth_table" the second way, "master_table" probably ought to be declared like one of these. (Deliberately ignoring cascading updates and deletes.)

CREATE TABLE master_table (
  master_directory varchar not null,
  master_image varchar not null,
  primary key (master_directory, master_image),
  foreign key (master_directory, master_image)
    references auth_table (directory, image)
);

CREATE TABLE master_table (
  id integer primary key,
  foreign key (id) references auth_table (id)
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM