假设存在查询,该查询计算给定点与存储在数据库中的点之间的距离。目的是找到给定的最近点
select x,y, get_distance(25,13,x,y) as dis
from points
order by dis
但作为一个条件,我想设置距离限制,以便只得到距离<1000
的结果select x,y, get_distance(25,13,x,y) as dis
from points
where dis <1000
order by dis
此查询的结果是: 错误:列“dis”不存在
所以我被迫写两次函数调用:
select x,y, get_distance(25,13,x,y) as dis
from points
where get_distance(25,13,x,y) <1000
order by dis
尽管如此,函数get_distance被声明为 immutable ,并且不会像在docs中声明的那样计算两倍,查询本身看起来很难看。
有没有办法在条件中使用 get_distance的结果作为dis 而不是两次写入?
答案 0 :(得分:1)
是
SELECT * FROM (
SELECT x, y, get_distance(25, 13, x, y) dis FROM points
) t
WHERE dis < 1000
ORDER BY dis