开发者

Converting nested Selects in WHERE .. OR .. to INNER JOINS

开发者 https://www.devze.com 2022-12-09 20:06 出处:网络
How would I convert the following to use INNER JOIN rather than nested SELECT? SELECT [Name].[NameV开发者_运维技巧alueID],

How would I convert the following to use INNER JOIN rather than nested SELECT?

SELECT 
    [Name].[NameV开发者_运维技巧alueID],
    [Name].[NameTypeID],
    [Name].[NameID],
    [Name].[Value]
FROM [Name] 
WHERE Name.NameTypeID IN ( SELECT NameTypeID FROM @tbNameType ) 
    OR Name.NameID IN ( SELECT NameID FROM @tbName) 


This one's tricky because it's an "OR" condition rather than an "AND". But I think this would do it:

SELECT 
        [Name].[NameValueID],
        [Name].[NameTypeID],
        [Name].[NameID],
        [Name].[Value]
FROM [Name] 
INNER JOIN  ( SELECT NameTypeID FROM @tbNameType ) t ON t.NameTypeID=Name.NameTypeID

UNION

SELECT 
        [Name].[NameValueID],
        [Name].[NameTypeID],
        [Name].[NameID],
        [Name].[Value]
FROM [Name]
INNER JOIN ( SELECT NameID FROM @tbName) t ON t.NameID = Name.NameID


SELECT DISTINCT
    Name.NameValueID,
    Name.NameTypeID,
    Name.NameID,
    Name.Value
FROM
    Name
    LEFT JOIN @tbNameType a ON a.NameTypeID=Name.NameTypeID
    LEFT JOIN @tbName b ON b.NameID=Name.NameID
WHERE a.NameTypeID IS NOT NULL OR b.NameID IS NOT NULL
0

精彩评论

暂无评论...
验证码 换一张
取 消