我被要求使用 PostgreSQL 创建一个表并使用以下信息:
The properties table should consist of: property_id (this should be the primary key as well as a unique number that increments automatically) name number of units owner_id (this should have the constraint NOT NULL) There should be also be a foreign key that references the owners table
我写了以下内容
apartmentlab=# CREATE TABLE properties (
apartmentlab(# PRIMARY KEY property_id SERIAL,
apartmentlab(# name TEXT,
apartmentlab(# num_of_units numeric,
apartmentlab(# FOREIGN KEY (owner_id) REFERENCES owners (owner_id) NOT NULL
apartmentlab(# );
我收到以下消息:
ERROR: syntax error at or near "property_id" LINE 2: PRIMARY KEY property_id SERIAL,
谁能告诉我 property_id 和我的语法有什么问题。我查看了文档,这看起来是正确的。
最佳答案
PRIMARY KEY
子句位于数据类型之后:
CREATE TABLE properties (
property_id SERIAL PRIMARY KEY,
name TEXT,
num_of_units numeric,
FOREIGN KEY (owner_id) REFERENCES owners (owner_id) NOT NULL
);
另请注意您在外键定义中的错误。您可能还需要在您的表中定义字段 owner_id
,其数据类型与被引用表中的数据类型相同。
关于postgresql - 使用 postgreSQL 创建表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42548212/