【问题标题】:How to get columns from other table with a foreign key?如何使用外键从其他表中获取列?
【发布时间】:2017-11-12 22:57:51
【问题描述】:

我有以下表格:

CREATE TABLE "itemDetails"
(
    id smallint,
    name character varying(32) NOT NULL,
    description character varying(255) NOT NULL,
    PRIMARY KEY (id)
)

CREATE TABLE items
(
    id int,
    "detailsId" smallint REFERENCES "itemDetails" (id),
    "ownerId" int,   -- REFERENCES users (id),
    "condition" int NOT NULL DEFAULT 100,
    PRIMARY KEY (id)
)

itemDetails 表存储了一个项目的所有静态信息,而items 表存储了一个项目的每个单独的实例,列如conditionownerId

如果我通过执行以下操作从哪里获取用户拥有的所有项目:

SELECT * FROM items WHERE "ownerId" = 5;

我如何使用外键获取这些自有项目的名称和描述?

【问题讨论】:

    标签: sql postgresql join foreign-keys


    【解决方案1】:

    使用普通连接:

    SELECT i.*, d.name, d.description
    FROM   items i
    JOIN   "itemDetails" d ON d.id = i."detailsId"
    WHERE  "ownerId" = 5;
    

    Read the manual about the FROM clause here.

    除此之外:我建议避免在 Postgres 中使用双引号 CaMeL-case 标识符。让您的生活更轻松。见:

    【讨论】:

    • 有效!谢谢你的提示,我一定会调查的。
    猜你喜欢
    • 1970-01-01
    • 2021-11-07
    • 2012-07-11
    • 2012-03-15
    • 1970-01-01
    • 1970-01-01
    • 2019-11-19
    • 2021-02-15
    • 2021-12-01
    相关资源
    最近更新 更多