使用string_agg时缺少表的FROM子句条目

时间:2017-04-28 06:01:08

标签: sql postgresql

我有这个查询试图搜索满足3个要求的课程。

select
    course.id,
    course.title,
    course.number,
    string_agg(requirement.description,'; ' order by requirement.description) 
from course
join
(
    select course.id, course.title, course.number
    from requirement join course_requirement 
        on (requirement.id=course_requirement.requirement)
    join course on (course.id=course_requirement.course) 
    where requirement.description='Human Behavior'
) as c1
    on (c1.id=course.id)
join
(
    select course.id, course.title, course.number 
    from requirement
    join course_requirement
        on (requirement.id=course_requirement.requirement)
    join course
        on (course.id=course_requirement.course) 
    where requirement.description='Intercultural'
) as c2
    on (c1.id=c2.id)
join
(
    select course.id, course.title, course.number 
    from requirement
    join course_requirement
        on (requirement.id=course_requirement.requirement)
    join course
        on (course.id=course_requirement.course) 
    where requirement.description='Religion'
) as c3
    on (c1.id=c3.id)
group by course.id, course.title, course.number;

但是,我收到此消息:ERROR:缺少FROM-clause条目表"要求" 第1行:... course.id,course.title,course.number,string_agg(requiremen ... 你能告诉我在哪里得到错误的查询吗?

非常感谢你!

1 个答案:

答案 0 :(得分:2)

我没有看到三个连接子查询的重点,这些子查询仅在WHERE子句中的需求描述中有所不同。相反,您可以尝试使用WHERE IN来捕获结果集中所需的三个描述的单个查询。这也解决了您使用string_agg()时遇到的问题,您尝试从外部查询中无法访问的子查询中聚合某些内容。

尝试以下查询:

select
    t1.id,
    t1.title,
    t1.number,
    string_agg(t3.description, '; ' order by t3.description) 
from course t1
inner join course_requirement t2
    on t1.id = t2.course
inner join requirement t3
    on t2.requirement = t3.id
where t3.description in ('Human Behavior', 'Intercultural', 'Religion')
group by t1.id, t1.title, t1.number;