内部联接到表依赖于第一个表列连接第二个或第三个表中的值

时间:2013-01-24 10:26:03

标签: sql sql-server-2008

我有四张表User,Destination,City and visited

如下

declare  @user table
 (
   UserId int identity(1,1) not null ,
   UserName nvarchar(500)
 )

 insert into @user (UserName) values ('rahul')
 insert into @user (UserName) values ('nitin')
 insert into @user (UserName) values ('yunus')

 declare @destination table 
  (
    destCode nvarchar(50),
    destName nvarchar(500)
  )

  insert into @destination select 'SWDP','ranthambore national park '
  insert into @destination select 'BTP','ghana national park '

  declare @city table 
   (
     cityId int identity(1,1) not null, 
     cityname nvarchar(500)
   )

 insert into @city select 'jaipur'
 insert into @city select 'delhi'

 -- visited table in which user id with either destCode or cityId

 declare @visited table 
   (
     UserId int , 
     LocationFrom nvarchar(500),
     LocationTo nvarchar(500),
     LocType nvarchar(50)
   )

  insert into @visited select '1','BTP','1','city'
  insert into @visited select '1','1','SWDP','dest'


  insert into @visited select '2','1','2','city'


  insert into @visited select '3','2','SWDP','dest'
  insert into @visited select '3','SWDP','BTP','dest'


 select * from @user 

 select * from @destination

 select * from @city

 select * from @visited

  select * from @visited as v
   inner join @user as u ON v.UserId=u.UserId

访问表中的位置类型列表示LocationTo类型。它的城市或位置。

现在我想加入这些表格,以便我可以获取用户从哪个城市或目的地开始的数据,然后转到哪个城市和目的地。

预期结果如下图所示

this is only for one user

这仅适用于一个用户,但我需要为所有用户提供相同的服务。

2 个答案:

答案 0 :(得分:2)

我不确定我是否正确理解了您的表结构 但正如我所看到的,表@destination既可以是起点也可以是终点? 并且LocType仅指定端点的类型(LocationTo中的@visited) 鉴于此,我必须假设@Visited.LocationFrom中的数值指定@city中的ID

然后此查询可能有用

  SELECT u.UserName,   
    CASE WHEN ISNUMERIC(v.LocationFrom) = 1 THEN (SELECT cityName FROM @city where cityId = cast(v.LocationFrom as int)) ELSE (SELECT destName FROM @destination where destCode = v.LocationFrom) END as LocationFrom,
    CASE WHEN ISNUMERIC(v.LocationTo) = 1 THEN (SELECT cityName FROM @city where cityId = cast(v.LocationTo as int)) ELSE (SELECT destName FROM @destination where destCode = v.LocationTo) END as LocationTo
    FROM @visited AS v
   inner join @user AS u ON v.UserId=u.UserId   

答案 1 :(得分:2)

这应该适合你:

;WITH Locations AS
   (SELECT
        CAST(CityID as nvarchar(50)) LocationId,
        CityName LocationName
    FROM
        @city
    UNION ALL
    SELECT
        DestCode,
        DestName
    FROM
        @destination)
    SELECT 
        Users.UserName,
        LocationsFrom.LocationName LocationFromName, 
        LocationsTo.LocationName LocationToName
    FROM 
        @visited Visited
        INNER JOIN Locations LocationsFrom ON LocationsFrom.LocationID = Visited.LocationFrom
        INNER JOIN Locations LocationsTo ON LocationsTo.LocationID = Visited.LocationTo
        INNER JOIN @user Users ON Visited.UserID = Users.UserID