我正在尝试使用连接,子查询和agregate函数编写一个复杂的POSTGRES查询。一切正常,但有一点。这是代码:
SELECT
table1.id AS id1,
table1.name AS name,
table1.table2_fkey AS id2
table2.name AS name2,
table2.id,
month_sum
FROM table1
LEFT JOIN table2 ON (table1.table2_fkey = table2.id)
INNER JOIN (
SELECT sum(months) AS month_sum FROM (
SELECT (month_1 + month_2 + month_3 + month_4 + month_5 + month_6 + month_7 + month_8 + month_9 + month_10 + month_11 + month_12) as months FROM table2_places_years WHERE table2_places_fkey IN (
SELECT id FROM table2_places WHERE table2_people_fkey IN (
SELECT id FROM table2_people WHERE table2_fkey = table2.id
)
)
) AS months
) AS month_sum ON (table2.id = id2)
(我简化了列和表的名称)
问题是第二个JOIN中的最后一个子查询无法访问第一个连接中的table2,因此会抛出错误。如果我从最后一个子查询中删除where子句,查询运行正常,但得到'table2_places_years'中所有行的总和。我想从与table2的当前条目相关联的行中得到总和(通过另外三个表与fkeys链接)。
有没有办法'让子查询知道'第一个连接子句中的列?
提前致谢!
注意:这段代码可能无法正常工作,因为我做了一些简化。
答案 0 :(得分:1)
如果数据允许,请使用连接重写查询。它看起来像这样:
join (
select table2_fkey, sum(…) …
from table2_places_years
join table2_places …
join table2_people …
group by table2_fkey
) month_sum on table2_fkey = table2.id
如果没有,您还可以将相关子查询放在select语句中:
select …,
(
select sum(…) …
) month_sum
from table1 left join table2 …
最后一种方法可能是横向连接。它可能看起来像这样:
SELECT
table1.id AS id1,
table1.name AS name,
table1.table2_fkey AS id2
table2.name AS name2,
table2.id,
month_sum
FROM table1
LEFT JOIN table2 ON (table1.table2_fkey = table2.id),
LATERAL (
SELECT sum(months) AS month_sum FROM (
SELECT (month_1 + month_2 + month_3 + month_4 + month_5 + month_6 + month_7 + month_8 + month_9 + month_10 + month_11 + month_12) as months FROM table2_places_years WHERE table2_places_fkey IN (
SELECT id FROM table2_places WHERE table2_people_fkey IN (
SELECT id FROM table2_people WHERE table2_fkey = table2.id
)
)
) AS months
) month_sum
http://www.depesz.com/2012/08/19/waiting-for-9-3-implement-sql-standard-lateral-subqueries/