代码之家  ›  专栏  ›  技术社区  ›  Salih Erikci

从另一个表中获取多列的值

sql
  •  0
  • Salih Erikci  · 技术社区  · 7 年前

    我有一个有两个字段的桌上城市,CityCode和RegionCode 我有另一个表代码,有两个字段Code和codemensing

    如果我必须从代码表中得到一个含义,我可以使用join来实现,但我不知道如何为这两列都获取值。

    City Table Data
    ------------------------
    CityCode     RegionCode
    34             53
    41             43
    
    Code Table Data
    -----------------
    Code        Meaning
    34          New York
    41          Boston
    53          North
    43          South
    
    
    Desired Output
    ------------------
    CityCode     RegionCode    Region   City
    34             53          North    New York
    41             43          South    Boston
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   Gordon Linoff    7 年前

    使用两个连接:

    select cc.meaning as city, cr.meaning as region
    from city c left join
         code cc
         on c.citycode = cc.code left join
         code cr
         on c.regioncode = cr.code
    
        2
  •  1
  •   Z .    7 年前

    select c.*, c1.data as city, c2.data as region
    from city_table c
    join code_table c1 on c1.code = c.city_code
    join code_table c2 on c2.code = c.region_code