使用计算距离的PostgreSQL Where子句

使用计算距离的PostgreSQL Where子句,postgresql,Postgresql,我有一个如下的PostgreSQL查询: SELECT *, 2 * 3961 * asin(sqrt((sin(radians((latitude - 40.2817993164062) / 2))) ^ 2 + cos(radians(40.2817993164062)) * cos(radians(latitude)) * (sin(radians((longitude - -111.720901489258) / 2))) ^ 2)) as distance, (SELECT jso

我有一个如下的PostgreSQL查询:

SELECT *, 
2 * 3961 * asin(sqrt((sin(radians((latitude - 40.2817993164062) / 2))) ^ 2 + cos(radians(40.2817993164062)) * cos(radians(latitude)) * (sin(radians((longitude - -111.720901489258) / 2))) ^ 2)) as distance, 
(SELECT json_agg(deals.*) FROM deals WHERE vendors.id = deals.vendorid) as deals FROM vendors  
WHERE ( category = 'Food' ) 
AND (distance < 80)  
AND (nationwide IS FALSE OR nationwide is NULL) 
ORDER BY featured ASC, created DESC, distance ASC
我使用第二个选择部分得到了以英里为单位的距离


问题是说和距离<80的部分我得到了以下错误:列距离不存在奇怪的是,如果我删除和距离<80,它就工作了,它也按距离正确排序,输出的数据也包括距离,因此,它正确地获取了距离,但出于某种原因,在WHERE子句中不允许我使用距离作为过滤器,我不知道为什么

距离只是一个别名。您可以尝试以下方法:

WITH vendors_distance as (
    SELECT *, 
    2 * 3961 * asin(sqrt((sin(radians((latitude - 40.2817993164062) / 2))) ^ 2 + cos(radians(40.2817993164062)) * cos(radians(latitude)) * (sin(radians((longitude - -111.720901489258) / 2))) ^ 2)) as distance
    FROM vendors  
    WHERE ( category = 'Food' ) 
    AND (nationwide IS FALSE OR nationwide is NULL) 
)
SELECT vendors_distance.*, 
    (SELECT json_agg(deals.*) FROM deals WHERE vendors_distance.id = deals.vendorid) as deals
FROM vendors_distance 
WHERE (distance < 80)  
ORDER BY featured ASC, created DESC, distance ASC