将IN子查询转换为内连接

时间:2011-10-19 14:42:34

标签: sql sql-server

可以将以下查询转换为使用内部联接而不是where IN子查询吗?

select i.*, it.*
from ItemTypes it
    inner join Items i on (i.itemTypeID = it.ItemTypeID)
where i.itemID IN (......)

我可能在子查询中返回了100个结果,我想避免在子查询中使用它。

3 个答案:

答案 0 :(得分:2)

您可以使用WITH common table expression (CTE)

;with SelectedItems (selectedIDs) as
(
    select distinct itemID from [...] where [...]
)
select i.*, it.*
from ItemTypes it
inner join Items i on i.itemTypeID = it.ItemTypeID
inner join SelectedItems on selectedIDs = i.itemID

您还可以定义一个带有索引的临时#Table来保存选择:

create table #SelectedItems
(
    selItemID int primary key clustered
)
insert into #SelectedItems (selItemID)
select [...]

select i.*, it.*
from ItemTypes it
inner join Items i on i.itemTypeID = it.ItemTypeID
inner join #SelectedItems si on si.selItemID = i.itemID

drop table #SelectedItems

但无论你做什么,都要小心测量任何改变之前和之后的表现。

答案 1 :(得分:0)

select i.*, it.*
from ItemTypes it
    inner join Items i on (i.itemTypeID = it.ItemTypeID)
    inner join (select itemID from Items where ...) i2 ON i.itemID = i2.itemID

答案 2 :(得分:0)

你可以像这样写

select i.*, it.*
from ItemTypes it
    inner join Items i on (i.itemTypeID = it.ItemTypeID)
    inner join (select distinct itemID from [...] where [...]) i2
        on (i.itemID = i2.itemID)

但我怀疑你会从中获益。毕竟,现代数据库倾向于为常见查询和子句找到最佳执行计划。但是,在这种情况下,可能需要额外的工作来使用distinct运算符来删除重复项