我尝试在
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子句中使用函数结果而不调用它两次? 谢谢!
避免拨打
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
是一种更干净的方法。
您也可以使用横向
SELECT *
FROM clinics,
LATERAL (SELECT distance_between_objects(1, id, 7, 3) AS dist) l
WHERE l.dist <= 1;
以前从未见过横向。我一定要尝试一下!
您可以在where子句中使用该函数:
SELECT clinics.*, distance_between_objects(1, id, 7, 3) AS dist
FROM clinics
WHERE distance_between_objects(1, id, 7, 3)<=1;