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

时间:2018-08-13 15:10:30

标签: sql

我有一个表City,其中有两个字段CityCode和RegionCode 我有另一个具有两个字段Code和CodeMeaning的表Code

我想写一条选择语句,显示每个城市的cityCode,regionCode及其含义。

如果我必须从代​​码表中获得一个含义,我可以使用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 个答案:

答案 0 :(得分:2)

使用两个联接:

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

答案 1 :(得分:1)

这是一个较差的数据库设计,但是您可以通过2次联接来获取数据到代码表:

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
相关问题