我有两张表:一张是大城市附近的气象站列表,一张是距离城市的距离,另一张是每个气象站的平均天气。我想做一个连接,比如显示离旧金山最近的气象站的天气数据。
示例表距离
select * from distances limit 3;
city | station | distance
----------+-------------+-----------
New York | USC00280721 | 62.706849
New York | USC00280729 | 91.927548
New York | USC00280734 | 91.865147
示例表weatherdata
select * from weatherdata where id='USC00280734' limit 3;
id | date | element | data_value | mflag | qflag | sflag | observation_time
-------------+------------+---------+------------+-------+-------+-------+------------------
USC00280734 | 2001-01-01 | TMAX | -6 | | | 0 | 07:00:00
USC00280734 | 2001-01-01 | TMIN | -61 | | I | 0 | 07:00:00
USC00280734 | 2001-01-01 | TOBS | -89 | | I | 0 | 07:00:00
我希望能够根据城市名称进行SQL选择。
发布于 2021-06-10 18:41:53
对于一个城市,我建议:
select wd.*
from (select d.*
from distances d
where city = 'San Francisco'
order by distance
limit 1
) d join
weatherdata wd
on wd.id = s.station;
对于所有或多个城市,我只需使用distinct on
对其进行调整。
select wd.*
from (select distinct on (city) d.*
from distances d
order by city, distance
) d join
weatherdata wd
on wd.id = s.station;
这两个版本都可以在distances(city, distance)
上使用索引。
发布于 2021-06-10 18:33:23
你可以在下面试试-
select * from weatherdata wd where id in
(
select station
from distances d
where city = 'San Francisco'
and distance in (Select min(distance) from distances where city = 'San Francisco')
);
发布于 2021-06-10 18:34:13
我会创建一个第三个连接,从距离只与城市和最小(距离),并加入回距离表。
select wd.*
from weatherdata wd
join distances d on d.station = wd.id
join (select City, min(distinace) mindistance
from distances
group by city) A on a.city = d.city
and a.mindistance = d.distance
where d.city = 'San Francisco'
https://stackoverflow.com/questions/67926553
复制相似问题