2016-09-27 72 views
0

我有一个问题链接两个表,其中需要多次连接1个字段。加入两个SQL表,其中一个连接字段被多次使用

两个表如下:

Venue_Location_Master

  • ID
  • LOCATION_NAME
  • UNID
  • is_warehouse

Bag_Dim

  • EVENT_ID
  • Bag_type
  • bag_id
  • label_id
  • CREATED_DATE
  • created_by_employee
  • origin_location_id
  • destination_location_id
  • composition_id

该表的连接origin_location_id或destination_location_id到Venue_Location_Master.id

我试图构建一个返回查询:

  • bag_id
  • created_by_employee
  • event_name
  • origin_location_id
  • Venue_Location_Master.location_name(ORIGIN_NAME)
  • destination_location_id
  • Venue_Location_Master.location_name(DESTINATION_NAME)

我用工会试过,但返回所需的数据,而是跨越两行(见下文)。任何人有任何建议?

SELECT [bag_id], 
[created_date], 
[created_by_employee], 
[origin_location_id], 
ISNULL([venue_location_master].[location_name], 'NULL') AS [origin_location_name], 
[destination_location_id], 
ISNULL([venue_location_master].[location_name], 'NULL') AS [destination_location_name]  
,ISNULL([event_master].[event_name], 'NULL') AS [event_name] 
FROM [variance_cash].[dbo].[Bag_Dim] 
LEFT JOIN [verteda_rts_v4].[dbo].[venue_location_master] 
ON [Bag_Dim].[destination_location_id] = [venue_location_master].[id] 
LEFT JOIN [verteda_rts_v4].[dbo].[event_master] 
ON [Bag_Dim].[event_id] = [event_master].[id] 
WHERE [bag_id] = 'K5334' 
+1

左对齐SQL很难阅读。 – jarlh

+0

您想要将两列合并为一个列值(s)? –

+0

这个想法是为origin_location_id和destination_location_id返回一个带venue_location_master.location_name的行。我猜这可能需要给列提供一个别名来区分它们? – Sarah

回答

0

如果使用别名,则可以在同一张表上连接两次。

只要加入正确的领域,这应该做的伎俩。

SELECT 
    [bag_id], 
    [created_date], 
    [created_by_employee], 

    --origin 
    [origin_location_id], 
    --use table alias to get correct origin name 
    ISNULL(origin.[location_name], 'NULL') AS [origin_name], 

    --destination 
    [destination_location_id], 
    --use table alias to get correct destination name 
    ISNULL(destination.[location_name], 'NULL') AS [destination_name], 

    ISNULL([event_master].[event_name], 'NULL') AS [event_name] 
FROM [variance_cash].[dbo].[Bag_Dim] 

--join on destination, alias is... destination 
LEFT JOIN [verteda_rts_v4].[dbo].[venue_location_master] as destination 
     ON [Bag_Dim].[destination_location_id] = destination.[id] 

--join on origin, alias is... origin 
LEFT JOIN [verteda_rts_v4].[dbo].[venue_location_master] as origin 
     ON [Bag_Dim].[origin_location_id] = origin.[id] 

LEFT JOIN [verteda_rts_v4].[dbo].[event_master] 
    ON [Bag_Dim].[event_id] = [event_master].[id] 
WHERE [bag_id] = 'K5334' 
+0

完美。谢谢。这是给连接表一个别名,我不能得到我的头! – Sarah