简体   繁体   中英

How do I remove a nested select from this SQL statement

I have the following SQL:

SELECT * FROM Name 
INNER JOIN ( SELECT 2 AS item, NameInAddress.NameID as itemID, NameInAddress.AddressID
        FROM NameInAddress
        INNER JOIN Address ON Address.AddressID = NameInAddress.AddressID
        WHERE (Address.Country != 'UK')
) AS Items ON (Items.itemID = Name .Name ID)

I have been asked to remove the nested select and use INNER JOINS instead, as it will improve performance, but I'm struggling.

Using SQL Server 2008

Can anyone help?

Thanks!

Your query is not correct as you're using Items.itemID while it's not in the subselect

I guess this is what you meant:

SELECT Name.*
FROM Name
INNER JOIN NameInAddress
ON Name.NameID = NameInAddress.NameID
INNER JOIN Address 
ON Address.AddressID = NameInAddress.AddressID
WHERE (Address.Country != 'UK')

EDIT: The exact translation of your query would start with a SELECT Name.*, 2 as Item, NameInAddress.NameID, NameInAddress.AddressID though

It is one of those long-lived myths that nested selects are slower than joins. It depends completely on what the nested select says. SQL is just a declarative language to tell what you want done, the database will transform it into completely different things. Both MSSQL and Oracle (and I suspect other major engines as well) are perfectly able to transform correlated subqueries and nested views into joins if it is beneficial (unless you do really complex things which would be very hard, if possible, to describe with normal joins.

SELECT     2 AS Item, * 
FROM       Name 
INNER JOIN NameInAddress
ON         Name.NameID = NameInAddress.NameID
INNER JOIN Address 
ON         Address.AddressID = NameInAddress.AddressID
WHERE      Address.Country != 'UK'

PS: Don't use "*". This will increase performance too. :)

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