我正在使用 PostgreSQL 数据库。我需要创建一个 View ,其中包含一个在多个表上进行连接的查询,但我被困在了一个点上。请阅读下表定义和我创建的查询。
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 和我需要加入的一些其他字段。
我的要求是为此查询创建一个 View ,以便我仅将 subject_id
传递给 View (select * from testing_list_view where subject_uid='ff342ada-f5gb-44fb-bdth- 44e3n59f5448'
),我将获得申请给定科目的学生名单。但是,我被困在上面的连接查询中, subject_id
在连接子句中多次需要并且是硬编码的。所以,我无法让它成为一个观点。
我在考虑是否存在某种变量,使用它,在连接子句中,我将在必需的子句中使用该变量,并在查询 View 时将值 (subject_id) 传递给它。
如果需要更多说明,请告诉我。
最佳答案
您应该定义 View ,而不要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;
您在使用 View 时指定条件,例如
SELECT * FROM testing_list_view
WHERE subject_uid = 'ff342ada-f5gb-44fb-bdth-44e3n59f5448';
关于sql - 如何在 PostgreSQL 中使用带变量的内部连接创建 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54923131/