如何在PostgreSQL中使用带有变量的内连接创建视图?

问题描述 投票:1回答:1

我正在使用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子句中需要多次,并且是硬编码的。所以,我无法将其视为一种观点。

我在想是否存在某种变量,在join子句中,我将使用所需子句中的变量,并查询视图,我将传递值(subject_id)。

如果需要进一步澄清,请告诉我。

sql postgresql view
1个回答
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';
© www.soinside.com 2019 - 2024. All rights reserved.