【问题标题】:How do I join two tables based on a minimum value in the first table?如何根据第一个表中的最小值连接两个表?
【发布时间】:2021-06-10 18:19:07
【问题描述】:

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

示例表距离

select * from distances limit 3;

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

示例表天气数据

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 选择。

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    对于一个城市,我建议:

    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) 上的索引。

    【讨论】:

      【解决方案2】:

      你可以试试下面-

      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')
      );
      

      【讨论】:

        【解决方案3】:

        我会从距离创建第三个连接,仅包含城市和分钟(距离),然后连接回距离表。

        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'
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-05-05
          • 2021-11-11
          • 2021-11-17
          • 2021-01-14
          • 1970-01-01
          • 2020-11-29
          • 2020-04-08
          相关资源
          最近更新 更多