我有以下表格:
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
表存储项目的每个单独实例,其中包含condition
和{{1}等列}。
如果我通过执行以下操作来获取用户拥有的所有项目:
ownerId
如何使用外键获取这些拥有项目的名称和描述?
答案 0 :(得分:2)
使用普通联接:
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案例标识符。让您的生活更轻松。参见: