简体   繁体   中英

Convert Where IN sub-query to an inner join

Can the below query be converted to using an inner join instead of the where IN subquery?

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

I might have 100 results returned in the sub-query and I want to avoid having that in a sub-query.

You could use the 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

You could also define a temporary #Table with an index to hold the selections:

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

But whatever you do, be careful to measure performance before and after any change.

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

You could write it like this

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)

But I doubt you'll get benefits from this. After all, modern databases tend to find the optimal execution plan for common queries and clauses. In this case, however, extra work might be needed to get rid of duplicates using the distinct operator

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM