加入两个sql表,其中多次使用一个连接字段

时间:2016-09-27 10:14:38

标签: sql database

我在连接两个表时遇到问题,其中多次需要1个连接字段。

这两个表格如下:

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)

我尝试过使用union,但是会返回所需的数据,但会跨两行(见下文)。有人有什么建议吗?

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 个答案:

答案 0 :(得分: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'