将tbl1连接到select语句两次,并连接到也连接到tbl3的tbl2

时间:2017-06-21 08:13:58

标签: sql sql-server select join multiple-columns

我正在使用SQL server manger。

我有3张桌子

Tables snapshot and Query Aim

我需要一个查询来拉取t1并添加一个Origin Basin和一个Destination Basin。

到目前为止,我有以下内容:

  select T1.[Country (destination)], T3.AreaName
         From T1
         left outer join T2 on
         T1.[Country (destination)] = T2.CountryName
         inner join T3 on 
         T2.AreaID = T3.AreaID 
         inner join T3 on
         T2.AreaID = T3.AreaID

返回:

国家|区域 但是,我在第二个国家专栏中遇到这个问题。我相信你使用别名。我试过了:

    select (select AreaName
        FROM T3
        where T3.AreaID = T2.AreaID) as 'Area Imp',
            (select AreaID
                From T2
                where T2.CountryName = T1.[Country (origin)]) as 'x',
    (select AreaID
        From T2
        where T2.CountryName = T1.[Country (destination)]) as 'y'
    FROM T1

但我无法让它发挥作用。

3 个答案:

答案 0 :(得分:0)

这是你需要做的:

select t1.date, t1.country_destination, t1.country_origin, destination_area.AreaName as area_destination, origin_area.AreaName as area_origin
from t1 as t1 join t2 as destination on t1.country_destination = destination.countryname
              join t2 as origin on t1.country_origin = origin.countryname

              join t3 as destination_area on t2.areaid = destination_area.areaid
              join t3 as origin_area on t2.areaid = origin_area.areaid

您需要为t2t3两次加入同一个表,以便根据需要获得匹配的记录。 在编写查询时,通常会放置与连接目的匹配的别名(在本例中为destinationorigin)。

答案 1 :(得分:0)

我认为您尝试做的事情是这样的:

 select T1.*, T3dest.AreaName, T3orig.AreaName
 From
     T1
        inner join
     T2 T2dest on
        T1.[Country (destination)] = T2dest.CountryName
        inner join
     T3 T3dest on 
        T2dest.AreaID = T3dest.AreaID 
        inner join
     T2 T2orig on
        T1.[Country (origin)] = T2orig.CountryName
        inner join
     T3 T3orig on
        T2orig.AreaID = T3orig.AreaID

请注意,此刻我已切换到inner join。如果您确实需要left join语义,则需要对T2T3表的所有连接使用这些语义,或者需要更改连接顺序(以便相关{在尝试与T3联接之前,{1}}表连接T2。然而,从样本数据中不清楚是否需要这样做。

答案 2 :(得分:0)

试试这个,你仍然想加入区域ID

select T1.Date,T1.[Country (destination)], null [Country (origin)],  T3.AreaName [AreaName(Destination)], null [AreaName(Origin)]
         From T1
         left outer join T2 on
         T1.[Country (destination)] = T2.CountryName
         inner join T3 on 
         T2.AreaID = T3.AreaID 

union all

select T1.Date,null [Country (destination)],  t1.[Country (origin)],  Null [AreaName(Destination)], t3. [AreaName(Origin)]
         From T1
         left outer join T2 on
         T1.[Country (Origin)] = T2.CountryName
         inner join T3 on 
         T2.AreaID = T3.AreaID