PostgreSQL-为具有多对多关系的多个表创建数据库视图

时间:2018-08-13 06:41:42

标签: postgresql database-design

在我的PostgreSQL数据库中,我有一个“项目”表,定义为

CREATE TABLE item
(
  "objectId" text NOT NULL,
  "createdAt" timestamp with time zone,
  "updatedAt" timestamp with time zone,
  item_name text,
  is_parent boolean,
  CONSTRAINT "ITEM_pkey" PRIMARY KEY ("objectId")
);

该表同时包含父项和子项,并在“ is_parent”列中对其进行声明。

另一个表定义了一个多对多关系,其中父项可以有多个子项,子项也是如此。

CREATE TABLE item_pa_ch_rel
(
  "objectId" text NOT NULL,
  "createdAt" timestamp with time zone,
  "updatedAt" timestamp with time zone,
  item_pa character(10),   -- foreign key of item.objectId for a parent item
  item_ch character(10),   -- foreign key of item.objectId for a child item
  CONSTRAINT item_pa_ch_rel_pkey PRIMARY KEY ("objectId")
);

我想创建一个数据库视图,该视图将连接item.objectId上的两个表并包含parent_objectId,parent_item_name,child_objectId和child_item_name:

parent_objectId, parent_item_name, child_objectId, child_item_name

1 个答案:

答案 0 :(得分:1)

最终我得到了答案:

DROP VIEW vw_test;

CREATE OR REPLACE VIEW vw_test AS 
 SELECT t1.item_name AS p_item_name,
    t2."createdAt",
    t2."updatedAt",
    t3.item_name AS c_item_name,
    t2."objectId"
   FROM item t1 INNER JOIN item_pa_ch_rel t2 on t1."objectId" = t2.item_pa::text
   INNER JOIN item t3 on t2.item_ch::text = t3."objectId";

ALTER TABLE vw_test
  OWNER TO gc;