简体   繁体   English

PostgresQL外键语法错误

[英]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. 因此, 可能需要将“ auth_table”声明为以下方式之一。 (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. 假设您想用第二种方式声明“ auth_table”,那么“ master_table”可能应该像其中一种那样声明。 (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)
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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