首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何根据第一个表中的最小值连接两个表?

如何根据第一个表中的最小值连接两个表?
EN

Stack Overflow用户
提问于 2021-06-10 18:19:07
回答 3查看 40关注 0票数 0

我有两张表:一张是大城市附近的气象站列表,一张是距离城市的距离,另一张是每个气象站的平均天气。我想做一个连接,比如显示离旧金山最近的气象站的天气数据。

示例表距离

代码语言:javascript
运行
复制
select * from distances limit 3;

   city   |   station   | distance  
----------+-------------+-----------
 New York | USC00280721 | 62.706849
 New York | USC00280729 | 91.927548
 New York | USC00280734 | 91.865147

示例表weatherdata

代码语言:javascript
运行
复制
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选择。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2021-06-10 18:41:53

对于一个城市,我建议:

代码语言:javascript
运行
复制
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对其进行调整。

代码语言:javascript
运行
复制
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)上使用索引。

票数 1
EN

Stack Overflow用户

发布于 2021-06-10 18:33:23

你可以在下面试试-

代码语言:javascript
运行
复制
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')
);
票数 1
EN

Stack Overflow用户

发布于 2021-06-10 18:34:13

我会创建一个第三个连接,从距离只与城市和最小(距离),并加入回距离表。

代码语言:javascript
运行
复制
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'
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67926553

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档