子查询中的 Postgresql 列不存在

问题描述 投票:0回答:1

我需要在 select 语句中包含 subselect,这在 Mysql 中很常见,但在 Postgresql 中不起作用。 我收到错误未定义列:7 错误:“count_receipts”列不存在

select "organizations".*, (
    SELECT count(*) AS count_receipts FROM companies
            JOIN receipts ON receipts.company_id = companies.id
            WHERE companies.organization_id = organizations.id
            GROUP BY companies.organization_id
) as count_receipts 
from "organizations" 
where count_receipts >= 10 
AND count_receipts <= 20  

如果我删除 where 子句,一切正常,并且 count_receipts 列包含在结果中。但在哪里不起作用。

这个sql有什么问题?

sql postgresql subquery
1个回答
0
投票

不要将子查询用作列,而是在联接中使用它:

SELECT o.*, count_receipts
FROM organizations o
JOIN (
  SELECT c.organization_id, count(*) AS count_receipts 
  FROM companies c
  JOIN receipts r ON r.company_id = c.id
  GROUP BY c.organization_id
) AS s on s.organization_id = o.id
WHERE count_receipts >= 10 
AND count_receipts <= 20;
© www.soinside.com 2019 - 2024. All rights reserved.