我可以为内部连接操作选择不同的表吗?

时间:2014-04-23 10:46:29

标签: tsql

这是我的T-SQL

select Id,Profile,Type ,
       case Profile 
         when 'Soft' then 'SID' 
         when 'Hard' then 'HID' 
       end as [Profile] 
from ProductDetail p1
inner join [tableA or tableB] on xxxxxxxx 

我希望在tableA时加入Profile = Soft并在tableB时加入Profile = Hard,如何只在一个批次中使用T-SQL?

由于

3 个答案:

答案 0 :(得分:1)

您无法直接执行此操作,但可以通过外部联接实现相同的效果

select Id,Profile,Type ,
   case Profile 
     when 'Soft' then 'SID' 
     when 'Hard' then 'HID' 
   end as [Profile] 
   from ProductDetail p1
   left outer join tableA ON tableA.x = p1.x AND p1.Profile = 'Soft'
   left outer join tableB ON tableB.x = p1.x AND p1.Profile = 'Hard'
   where
where
    (tableA.x IS NOT NULL and p1.Profile = 'Soft')
    or (tableB.x IS NOT NULL and p1.Profile = 'Hard')   

答案 1 :(得分:1)

当然,您可以为内部联接操作选择不同的表,但必须基于某些条件或变量。 例如:

select Id,Profile,Type ,
       case Profile 
         when 'Soft' then 'SID' 
         when 'Hard' then 'HID' 
       end as [Profile] 
       from ProductDetail p1
inner join tableA A
  on Profile='Soft'
    AND <any other Condition>

UNION 

select Id,Profile,Type ,
       case Profile 
         when 'Soft' then 'SID' 
         when 'Hard' then 'HID' 
       end as [Profile] 
       from ProductDetail p1
inner join tableB B
  on Profile='Hard'
    AND <any other Condition>

答案 2 :(得分:1)

您可以在单个语句中执行此操作,并在连接中使用相同或类似的case语句。下面是使用临时表的示例代码,这些表连接到使用UNION合并为单个结果集的2个不同引用表

DECLARE @ProductDetail TABLE (Id INT, sProfile VARCHAR(100), StID INT, HdID INT)
DECLARE @TableA TABLE (StId INT, Field1 VARCHAR(100))
DECLARE @TableB TABLE (HdId INT, Field1 VARCHAR(100))

INSERT INTO @ProductDetail (Id, sProfile, StID , HdID ) VALUES (1,'Soft',1,1)
INSERT INTO @ProductDetail (Id, sProfile, StID , HdID ) VALUES (2,'Hard',2,2)

INSERT INTO @TableA (StId,Field1) VALUES (1,'Soft 1')
INSERT INTO @TableA (StId,Field1) VALUES (2,'Soft 2')
INSERT INTO @TableB (HdId,Field1) VALUES (1,'Hard 1')
INSERT INTO @TableB (HdId,Field1) VALUES (2,'Hard 2')

SELECT 
    p1.Id,p1.sProfile,
    CASE 
        WHEN p1.sProfile = 'Soft' THEN StID
        WHEN p1.sProfile = 'Hard' THEN HdId
    END AS [Profile] 
    ,ReferenceTable.FieldName
FROM 
    @ProductDetail p1
INNER JOIN 
    (
    SELECT  StID    AS  id, 'Soft' AS sProfile, Field1 AS FieldName
    FROM    @TableA AS tableA

    UNION ALL

    SELECT HdID AS  id, 'Hard' AS sProfile, Field1 AS FieldName
    FROM    @TableB AS tableB
    )
    AS ReferenceTable
    ON 
    CASE 
        WHEN p1.sProfile = 'Soft' THEN StID
        WHEN p1.sProfile = 'Hard' THEN HdID
    END                                         =   ReferenceTable.Id
AND p1.sProfile = ReferenceTable.sProfile

这将返回以下结果集:

Id  sProfile    Profile FieldName
1   Soft    1   Soft 1
2   Hard    2   Hard 2