在“选择查询”中使用别名

时间:2011-11-03 11:54:06

标签: sql sql-server oracle

我需要问一下如何在Select Query中使用Alias,

我需要这个

SELECT (Complex SubQuery) AS A, (Another Sub Query WHERE ID = A) FROM TABLE

3 个答案:

答案 0 :(得分:13)

你不能这样做:

SELECT (Complex SubQuery) AS A, (Another Sub Query WHERE ID = A) FROM TABLE

但你可以这样做:

SELECT (Another Sub Query WHERE ID = A.somecolumn)
FROM table
JOIN SELECT (Complex SubQuery) AS A on (A.X = TABLE.Y)

或者

SELECT (Another Sub Query)
FROM table
WHERE table.afield IN (SELECT Complex SubQuery.otherfield)

问题是你不能在SELECT和WHERE子句中引用这样的别名,因为它们在select或执行部件时不会被评估。
您也可以使用having子句,但有子句不使用索引,应尽可能避免使用。

答案 1 :(得分:2)

您可以像这样重写您的查询

SELECT Complex.A, (Another Sub Query WHERE ID = Complex.A)
FROM TABLE
CROSS JOIN ((Complex SubQuery) AS A) Complex

答案 2 :(得分:0)

您可以使用的另一种解决方案:

SELECT (Complex SubQuery) AS A, (Another Sub Query WHERE ID = A) 
FROM 
TABLE MAIN
OUTER APPLY (SELECT (Complex SubQuery) AS A)