SQL Server - 多个FROM关键字?

时间:2013-10-18 14:02:02

标签: sql sql-server

搜索词对谷歌来说显然是模棱两可的。我正在看一个SQL调用,它有2个FROM关键字?我以前从未见过这个,有人可以解释一下吗?

SELECT TOP(5)  SUM(column) AS column, column
FROM ( SELECT DISTINCT column, column, column
FROM ((((((table table 
INNER JOIN table table ON (column = column
AND column = 2 
AND column != '' )) 
INNER JOIN table table ON (column   = column 
AND (column = 144 OR column = 159 OR column = 162 OR column = 164 OR column = 163 OR column  = 1 OR column = 2 OR column = 122 OR column = 155 OR column = 156 )))
inner join table table ON (column = column 
AND column  = 0 ))
INNER JOIN table  ON (column = column  ))
INNER JOIN table table ON ( column  = column  
AND (column   = 102 OR column  = 103 )))
INNER JOIN table table ON (column  = column  ))) TempTable  
GROUP BY column  ORDER BY column  desc 

您会注意到多个FROM关键字。它运行得很好。只是好奇目的是什么。

4 个答案:

答案 0 :(得分:5)

这被称为subquery。您可以在主查询中使用subquery 因此子查询产生了多个FORM子句。

答案 1 :(得分:3)

SQL支持SELECT来自另一个嵌套SELECT的结果。如前所述,嵌套的SELECT称为子查询。

有关子查询的更多详细信息及其在MSSQL Server中的使用示例,请访问http://technet.microsoft.com/en-us/library/ms189575(v=sql.105).aspx

用于选择别名列的子查询:

USE AdventureWorks2008R2;
GO
SELECT Ord.SalesOrderID, Ord.OrderDate,
    (SELECT MAX(OrdDet.UnitPrice)
     FROM AdventureWorks.Sales.SalesOrderDetail AS OrdDet
     WHERE Ord.SalesOrderID = OrdDet.SalesOrderID) AS MaxUnitPrice
FROM AdventureWorks2008R2.Sales.SalesOrderHeader AS Ord

WHERE子句中使用子查询(来自http://www.codeproject.com/Articles/200127/SQL-Joins-and-Subqueries

-- Use a Subquery
SELECT * FROM AdventureWorks.Person.Address 
WHERE StateProvinceID IN
(
    SELECT StateProvinceID 
    FROM AdventureWorks.Person.StateProvince 
    WHERE StateProvinceCode = 'CA'
)
-- Use a Join
SELECT addr.* 
FROM AdventureWorks.Person.Address addr
INNER JOIN AdventureWorks.Person.StateProvince state 
ON addr.StateProvinceID = state.StateProvinceID
WHERE state.StateProvinceCode = 'CA'

答案 2 :(得分:2)

您在子查询中看到FROM个子句。如果您将查询列表,则可能更明显

SELECT TOP(5)  SUM(column) AS column, column
FROM ( 
    SELECT DISTINCT column, column, column
    FROM ((((((table table 
    ...
    INNER JOIN table table ON (column  = column  ))) TempTable 
GROUP BY column  
ORDER BY column  desc

答案 3 :(得分:2)

SQL被称为结构化查询语言的原因是:它允许您制定使用其他查询作为其来源的查询,从而创建分层查询结构。

这是一种常见做法:每个FROM关键字实际上与其自己的SELECT配对,使内部查询成为外部查询的来源。

正确的格式化将帮助您了解正在发生的事情:缩进内部SELECT可帮助您查看查询的结构,从而更容易理解哪个部分用作其他部分的来源:

SELECT TOP(5)  SUM(price) AS total_price, item_id
FROM ( -- The output of this query serves as input for the outer query
     SELECT price, item
     FROM order -- This may have its own selects, joins, etc.
     GROUP BY order_id
)
GROUP BY item_id