postgresql - 使用 postgreSQL 创建表

标签 postgresql

我被要求使用 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/

相关文章:

python - 使用 Postgres 的 SQLAlchemy 中两个日期之间的平均天数

php - 将特殊字符插入 Postgresql 数据库

postgresql - 在 postgresql 函数中抛出异常

sql - Postgres Inner join insert into 和 select from 语法

postgresql - 如何在postgresql中的extract()上添加索引

json - 将 JSONB 转换为缩小(无空格)字符串

javascript - 无法连接到 dockerized postgresql 服务器

sql - Postgres 表名是否保证在模式中是唯一的?在数据库中?

node.js - 无法使用 Sequelize ORM 连接到 AWS RDS

ruby-on-rails - Heroku - ActiveRecord::StatementInvalid(PG::错误:错误:列 "requested"不存在