2

搜索词对谷歌来说显然是模棱两可的。我正在查看一个 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

4 回答 4

7

这称为subquery. 您可以subquery在主查询中使用因此子查询制作了多个 FORM 子句。

于 2013-10-18T14:06:17.387 回答
3

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

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

正确的格式可以帮助你理解正在发生的事情:缩进 inner SELECTs 可以帮助你查看查询的结构,从而更容易理解哪个部分用作其他部分的来源:

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
于 2013-10-18T14:10:29.267 回答
3

SQL 支持SELECT从另一个嵌套的结果中进行 ing 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'
于 2013-10-18T14:12:19.987 回答
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
于 2013-10-18T14:09:31.457 回答