【发布时间】:2019-02-28 10:11:01
【问题描述】:
我正在使用 PostgreSQL 数据库。我需要创建一个视图,该视图由多个表上的连接查询组成,但我被困在一个点上。请阅读下表定义和我创建的查询。
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) 传递给它。
如果需要进一步说明,请告诉我。
【问题讨论】:
-
视图不能有参数,但你可以创建一个 SQL 函数 (
returns table (...)),它将参数作为输入并简单地返回查询结果 -
在这里查看答案 - stackoverflow.com/questions/11401749/…
-
@JosMac 看起来与我的问题有关。让我试试这个问题的解决方案。
标签: sql postgresql view