如何正确连接可能返回多行的表

时间:2014-12-04 11:02:34

标签: sql sql-server stored-procedures join

我有一个表项目,其中包含以下列:

  

ItemId || AdminUserID || ITEMNAME

我尝试使用ItemAttributes加入它:

  

ItemAttributeId || ItemId ||的AttributeValue

其中一个ItemId可以分配多个ItemAttributeId值。

我创建了从两个表中检索项目值的过程:

 SELECT 
    i.ItemID,
    i.AdminUserID,
    i.ItemName,
    attr1.AttributeValue as IsForEmailRobotProcessingValue,
    attr2.AttributeValue as RobotScheduledHoursValue -- HERE IS THE PROBLEM
FROM [dbo].[Items] i WITH (NOLOCK)
    LEFT JOIN [dbo].ItemAttributes attr1 WITH(NOLOCK)
        ON attr1.ItemID = i.ItemID and attr1.ItemAttributeID = 1
    LEFT JOIN [dbo].ItemAttributes attr2 WITH(NOLOCK)
    ON attr2.ItemID = i.ItemID and attr2.ItemAttributeID = 2
WHERE ((attr1.AttributeValue IS NOT NULL AND attr1.AttributeValue = 'true') OR 
    @OnlyForEmailRobotProcessing = 0)
ORDER BY ItemName

我在这里不喜欢的是,我将LEFT JOIN两次放在同一个表中,并根据相同的ItemId为每个连接创建不同的别名。有没有更好的方法LEFT JOIN只有一次,并为每个ItemAttributeId创建了两个不同的别名?谢谢!

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT 
    i.ItemID,
    i.AdminUserID,
    i.ItemName,
    attr1.AttributeValue1 as IsForEmailRobotProcessingValue,
    attr1.AttributeValue2 as RobotScheduledHoursValue 
FROM [dbo].[Items] i WITH (NOLOCK)
    LEFT JOIN
            (select ItemId,  (select AttributeValue 
                              from  [dbo].ItemAttributes a
                              where a.ItemId = b.ItemId and a.ItemAttributeID = 1) as AttributeValue1,
                              (select AttributeValue 
                              from  [dbo].ItemAttributes c
                              where c.ItemId = b.ItemId and c.ItemAttributeID = 2) as AttributeValue2
             from    [dbo].ItemAttributes b  WITH(NOLOCK)
             where b.ItemId = i.ItemID  and b.ItemAttributeID in (1,2)

                ) attr1 on i.ItemId  = attr1.ItemId

WHERE ((attr1.AttributeValue IS NOT NULL AND attr1.AttributeValue = 'true') OR 
    @OnlyForEmailRobotProcessing = 0)
ORDER BY ItemName