from
中的Transact SQL语句Select
语句是什么意思?select语句中的select语句是什么意思?
我的意思是这样
.. from (
select ..
)
另外,我需要知道,如果语句是坏的性能。您能否在Transact SQL中为我提供有关此主题的官方文档的链接?
from
中的Transact SQL语句Select
语句是什么意思?select语句中的select语句是什么意思?
我的意思是这样
.. from (
select ..
)
另外,我需要知道,如果语句是坏的性能。您能否在Transact SQL中为我提供有关此主题的官方文档的链接?
我想你是在谈论subquery
。子查询用于返回将在主查询中使用的数据作为条件,以进一步限制要检索的数据。
请参考以下链接: - http://www.tutorialspoint.com/sql/sql-sub-queries.htm
你会发现很多的信息,这与快速搜寻。例如,参见 Subquery Fundamentals从MSDN
子查询是嵌套在SELECT,INSERT,UPDATE内, 或DELETE语句,或其它子查询内的查询。子查询可以是 在任何允许使用表达式的地方使用。
为什么downvote? – RedFilter
参见this link on MSDN about Subquery Fundamentals。
子查询可以很好,但要警告他们没有编入索引。如果查询的外部部分必须加入子查询的结果,性能可能会受到影响。请注意,查询优化器也可能为您的查询选择不同的执行顺序,因此即使您从子查询“开始”,优化器也可能在其他位置启动查询并加入到您的子查询中。
Correlated Subqueries(Joe Stefanelli首先在上面的注释中链接到这里)是另一个性能问题。任何时候你有一个查询必须重复执行一次外部查询的结果,性能将会受到影响。
看到这个link about Common Table Expressions (CTEs)。 CTE可能是编写查询的更好方法。子查询的其他替代方案包括@table variables和。
子查询的最常见用法之一是更新表时。 UPDATE
语句的SET列表中不能有聚合函数。您必须计算子查询中的聚合,然后再回到主查询来更新表。例如:
-- A table of state and the total sales per state
declare @States table
(
ID varchar(2) primary key,
totalSales decimal(10,2)
)
-- Individual sales per state
declare @Sales table
(
salesKey int identity(1,1) primary key,
stateID varchar(2),
sales decimal(10,2)
)
-- Generate test data with no sales totalled
insert into @States (ID, totalSales)
select 'CA', 0
union select 'NY', 0
-- Test sales
insert into @Sales (stateID, sales)
select 'CA', 5000
union select 'NY', 5500
-- This query will cause an error:
-- Msg 157, Level 15, State 1, Line 13
-- An aggregate may not appear in the set list of an UPDATE statement.
update @States
set totalSales = SUM(sales)
from @States
inner join @Sales on stateID = ID
-- This query will succeed, because the subquery performs the aggregate
update @States
set totalSales = sumOfSales
from
(
select stateID, SUM(sales) as sumOfSales
from @Sales
group by stateID
) salesSubQuery
inner join @States on ID = stateID
select * from @States
好的,你能提供一个好的和坏的使用子查询的例子吗? –
有时称为嵌套SELECT,或子查询,或可能是临时表,甚至内联视图。如果您发布整个查询,则可能可以获得有关使用更多常规联接的版本的帮助。 – Randy
“官方”文档:[子查询基础知识](http://msdn.microsoft.com/en-us/library/ms189575.aspx)。处理[相关子查询](http://msdn.microsoft.com/zh-cn/library/ms187638.aspx)时,您经常遇到性能问题。 –
问题中给出的例子实际上是一个“派生表”,而不是子查询。 –