如何从两个不同的 table 中获取最近城市的距离并将其合并到 PostgreSQL 中的 1 列中

How to get distance for the nearest city from Two different table and combining it into 1 column in PostgreSQL

我现在在这个模式中被困了好几天。

我正在尝试在与其他 2 table 不同的 table 中填充距离列。在 table 里面有纬度、经度、城市 ID、距离和位置 ID。

这是我要填充的当前 table

这是我可以用来计算距离的两个 tables

LocationID与第一个ID相同table 为了计算到最近城市的距离,我使用经纬度计算它,这就是我的代码最近距离的样子

select location_id, distance
from (SELECT  t.table1.location_id as location_id,
                ( 6371 * acos( cos( radians(6.414478) ) * 
                    cos( radians(t.table1.latitude::float8) ) * 
                        cos( radians(t.table1.longitude::float8) - radians(12.466646) )
                            + sin( radians(6.414478) ) * sin( radians(t.table1.latitude::float8) ) ) ) AS distance 
    FROM t.table1
    INNER JOIN t.table2
    on t.table1.location_id = t.table2.id
) km 
group by location_id, distance
Having distance < 2000 
order by distance limit 20;

但 table 只有 returns 空值

我正在为这段代码使用 PostgreSQL,用于可视化的应用程序是元数据库。

我建议您使用 PostGIS 扩展中的 ST_Distance 函数来计算距离,而不是自己动手。它会更容易,而且肯定会快得多。

编辑:可能误解了初衷。
这应该有效:

select d.city_id, d.distance, latitude,location_id, longitude 
from t.table1
left join lateral (
    select city_id, distance from (
        select location_id city_id, ( 6371 * acos( cos( radians(table3.latitude) ) * 
                        cos( radians(t.table1.latitude::float8) ) * 
                            cos( radians(t.table1.longitude::float8) - radians(table3.longitude) )
                                + sin( radians(table3.latitude) ) * sin( radians(t.table1.latitude::float8) ) ) ) AS distance 
        from t.table3
    ) d
    where distance < 2000
    order by distance 
    limit 1
) cities on true 

试试吧。
最好的问候,
比亚尼