简体   繁体   English

如何从此SQL语句中删除嵌套选择

[英]How do I remove a nested select from this SQL statement

I have the following SQL: 我有以下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. 我被要求删除嵌套的select并改用INNER JOINS,因为它可以提高性能,但是我很挣扎。

Using SQL Server 2008 使用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 您的查询不正确,因为您不在Items.itemID ,而是使用Items.itemID

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 编辑:查询的确切翻译将以SELECT Name.*, 2 as Item, NameInAddress.NameID, NameInAddress.AddressID

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. SQL只是一种声明性语言,用来告诉您要完成的工作,数据库会将其转换为完全不同的内容。 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. 如果有好处的话,MSSQL和Oracle(我也怀疑其他主要引擎)都能够完美地将相关的子查询和嵌套的视图转换为联接(除非您做的事情很复杂,如果可能的话,很难用常规方法描述)。连接。

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 "*". PS:请勿使用“ *”。 This will increase performance too. 这也将提高性能。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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