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

时间:2017-11-23 12:49:35

标签: postgresql select where-clause sql-function

我试图在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子句中使用函数结果吗? 谢谢!

3 个答案:

答案 0 :(得分:2)

避免两次致电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方法。

答案 1 :(得分:2)

您也可以使用LATERAL

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

答案 2 :(得分:0)

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

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