如何在PostgreSQL中使用WHERE EXISTS在主查询中获取子查询列?

时间:2017-05-24 14:18:05

标签: node.js postgresql postgresql-9.4 pg

我遇到了JOIN需要更多时间的查询,我想用WHERE EXISTS代替JOIN,因为明智的表现EXISTSsub query's columns花费更少的时间它

我修改了查询并按预期执行但我无法在主查询中使用query

这是我的SELECT MAX(st.grade_level::integer) AS grades , scl.sid AS org_sourced_id FROM schedules_53b055b75cd237fde3af904c1e726e12 sch LEFT JOIN schools scl ON(sch.school_id=scl.school_id) AND scl.batch_id=sch.batch_id AND scl.client_id = sch.client_id AND sch.run_id = scl.run_id WHERE EXISTS (SELECT t.term_id,t.abbreviation FROM terms t WHERE (sch.term = t.term_id) AND t.batch_id=sch.batch_id AND t.client_id = sch.client_id AND t.run_id = sch.run_id) AND EXISTS (SELECT st.grade_level, st.sid FROM students st WHERE (sch.student_id=st.sid) AND st.batch_id= sch.batch_id AND st.client_id = sch.client_id AND st.run_id = sch.run_id) GROUP BY scl.sid , sch.course_name , sch.course_number, sch.school_id

ERROR: missing FROM-clause entry for table "st"
SQL state: 42P01
Character: 29

我收到了这个错误:

sub query

我这里仅使用一列作为样本,但我必须使用EXISTS中的更多字段。

我的主要目标是如何使用pg或任何更优化的替代解决方案来实现这一目标

我在Node.js使用Node.js模块,因为后端我正在使用JOIN

更新

使用SELECT MAX(st.grade_level::integer) AS grades , scl.sid AS org_sourced_id FROM schedules_53b055b75cd237fde3af904c1e726e12 sch LEFT JOIN schools scl ON(sch.school_id=scl.school_id) AND scl.batch_id=sch.batch_id AND scl.client_id = sch.client_id AND sch.run_id = scl.run_id LEFT JOIN terms t ON (sch.term = t.term_id) AND t.batch_id=sch.batch_id AND t.client_id = sch.client_id AND t.run_id = sch.run_id LEFT JOIN students st ON (sch.student_id=st.sid) AND st.batch_id= sch.batch_id AND st.client_id = sch.client_id AND st.run_id = sch.run_id GROUP BY scl.sid , sch.course_name , sch.course_number, sch.school_id

查询
@SET_MAKE@

0 个答案:

没有答案