Transact SQL 语句中的Select
语句from
是什么意思?
我的意思是这样的
.. from (
select ..
)
另外,我需要知道该语句是否对性能不利。您能否提供一个链接,指向 Transact SQL 中有关此主题的官方文档?
Transact SQL 语句中的Select
语句from
是什么意思?
我的意思是这样的
.. from (
select ..
)
另外,我需要知道该语句是否对性能不利。您能否提供一个链接,指向 Transact SQL 中有关此主题的官方文档?
我想你在谈论subquery
. 子查询用于返回将在主查询中使用的数据,作为进一步限制要检索的数据的条件。
请参考此链接:- http://www.tutorialspoint.com/sql/sql-sub-queries.htm
请参阅MSDN 上有关 Subquery Fundamentals 的此链接。
子查询可以很好,但要注意它们没有被索引。如果查询的外部部分必须连接到子查询的结果,性能可能会受到影响。请注意,查询优化器也可能为您的查询选择不同的执行顺序,因此即使您“从”子查询“开始”,优化器也可能在其他地方开始查询并加入您的子查询。
相关子查询(Joe Stefanelli 在上面的评论中首先在这里链接)是另一个性能问题。每当您有一个必须为外部查询的结果重复运行的查询时,性能都会受到影响。
请参阅有关公用表表达式 (CTE) 的链接。CTE 可能是编写查询的更好方法。子查询的其他替代方案包括@table variables和#temporary tables。
子查询最常见的用途之一是更新表时。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
通过快速搜索,您会找到很多关于此的信息。例如,请参阅 MSDN 中的子查询基础
子查询是嵌套在 SELECT、INSERT、UPDATE 或 DELETE 语句或另一个子查询内的查询。子查询可以在任何允许使用表达式的地方使用。