我正在使用PostgreSQL DB。我需要创建一个视图,该视图由带有多个表上的联接的查询组成,但是我被困在一个点上。请阅读下表定义和我创建的查询。
Tables:
Students
---------
id -> UUID
full_name -> VARCHAR
email_id -> VARCHAR
location -> VARCHAR
created_at -> timestamp
modified_at -> timestamp
Subjects
--------
id -> UUID
title -> VARCHAR
classroom -> VARCHAR
created_at -> TIMESTAMP
Applications
------------
id -> UUID
student_id -> FOREIGN KEY (Students.id)
subject_id -> FOREIGN KEY (Subjects.id)
verified -> BOOLEAN
application_response -> JSON
status_id -> FOREIGN KEY (ApplicationStatus.id)
created_at -> TIMESTAMP
ApplicationStatus
-----------------
id -> UUID
application_status -> VARCHAR
category -> VARCHAR
Scores
-------
student_id -> FOREIGN KEY (Students.id)
subject_id -> FOREIGN KEY (Subjects.id)
score -> NUMERIC
以下是我创建的SQL查询:
create or replace view testing_list_view as
select c.id as student_id,
a.subject_id as subject_uid,
c.full_name,
c.email_id,
c.created_at,
p.score,
s.application_status,
a.verified,
a.application_response
from students c
inner join scores p
on p.student_id=c.id and p.subject_id = 'ff342ada-f5gb-44fb-bdth-44e3n59f5448'
inner join applications a
on a.student_id = c.id and a.subject_id= 'ff342ada-f5gb-44fb-bdth-44e3n59f5448'
inner join applicationstatus s
on s.id = a.status_id
where c.id in
(select student_id from applications where subject_id='ff342ada-f5gb-44fb-bdth-44e3n59f5448')
在这里,我将获得给定subject_id
的学生名单以及成绩,application_status和我需要加入的其他一些字段。
我的要求是为此查询创建一个视图,以便仅将subject_id
传递给视图(select * from testing_list_view where subject_uid='ff342ada-f5gb-44fb-bdth-44e3n59f5448'
),然后将获得已申请给定主题的学生的列表。 。但是,就像上面的联接查询一样,我被困在这里,subject_id
在联接子句中多次需要,并且是硬编码的。因此,我无法发表看法。
我在考虑是否存在某种变量,在join子句中将使用该变量,并在必需子句中使用该变量,并且在查询视图时,我将向其传递值(subject_id)。
请让我知道是否需要进一步澄清。
答案 0 :(得分:0)
您应在WHERE
子句和其他所有对subject_id
的限制下定义视图而没有:
create or replace view testing_list_view as
select c.id as student_id,
a.subject_id as subject_uid,
c.full_name,
c.email_id,
c.created_at,
p.score,
s.application_status,
a.verified,
a.application_response
from students c
inner join scores p
on p.student_id=c.id
inner join applications a
on a.student_id = c.id and a.subject_id = p.subject_id
inner join applicationstatus s
on s.id = a.status_id;
您使用视图时指定条件,例如
SELECT * FROM testing_list_view
WHERE subject_uid = 'ff342ada-f5gb-44fb-bdth-44e3n59f5448';