如何通过联接PostgreSQL中的两个表来创建视图?

时间:2018-11-28 21:13:26

标签: sql postgresql

我是PostgreSQL新手,并且有两个这样的表:

  1. Attendees(AttendeeId, Name)
  2. Couples(CoupleId, AttendeeIdMan, AttendeeIdLady)

如何创建这样的视图?

Attendees_Couple(CoupleId, Name_Man, Name_Lady)

现在,我想到了类似下面的内容,但是后来我被卡住了。

CREATE VIEW Attendees_Couple AS
SELECT a."Name"
FROM "Attendees" a, "Couples" c
WHERE a."AttendeeID" = c."AttendeeIdMan"....

任何提示或帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

您必须两次加入Attendees

CREATE VIEW "Attendees_Couple" AS
SELECT c."CoupleId",
       a1."Name" AS "Name_Man",
       a2."Name" AS "Name_Lady"
FROM "Couples" AS c
   JOIN "Attendees" AS a1 ON c."AttendeeIdMan"  = a1."AttendeeId"
   JOIN "Attendees" AS a2 ON c."AttendeeIdLady" = a2."AttendeeId";

帮个忙,并使用小写字母名称!