在 PostgreSQL 的 WHERE 子句中使用函数结果

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

我尝试在

where
子句中使用函数执行的结果,但没有成功:

SELECT clinics.*, distance_between_objects(1, id, 7, 3) AS dist FROM clinics WHERE dist<=1;

给我:

Column "dist" does not exists
。 引用它就像:

SELECT clinics.*, distance_between_objects(1, id, 7, 3) AS dist FROM clinics WHERE "dist"<=1;

也没有帮助。请告知Postgres是否有可能在WHERE子句中使用函数结果而不调用它两次? 谢谢!

postgresql select where-clause sql-function
4个回答
5
投票

避免拨打

distance_between_objects
两次:

--Subquery
SELECT * FROM (
    SELECT 
        *, 
        distance_between_objects(1, id, 7, 3) AS dist 
    FROM 
        clinics) AS clinics_dist 
WHERE 
    dist <= 1;

--CTE
WITH clinics_dist AS (
    SELECT 
        *, 
        distance_between_objects(1, id, 7, 3) AS dist 
    FROM 
        clinics
)
SELECT 
    * 
FROM 
    clinics_dist 
WHERE 
    dist <= 1;
在我看来,

CTE
是一种更干净的方法。


3
投票

您也可以使用横向

SELECT *
FROM clinics,
LATERAL (SELECT distance_between_objects(1, id, 7, 3) AS dist) l
WHERE l.dist <= 1;

0
投票

以前从未见过横向。我一定要尝试一下!


-1
投票

您可以在where子句中使用该函数:

SELECT clinics.*, distance_between_objects(1, id, 7, 3) AS dist 
FROM clinics 
WHERE distance_between_objects(1, id, 7, 3)<=1;
© www.soinside.com 2019 - 2024. All rights reserved.