简体   繁体   English

SELECT 语句的 SQL 别名

[英]SQL alias for SELECT statement

I would like to do something like我想做类似的事情

(SELECT ... FROM ...) AS my_select
WHERE id IN (SELECT MAX(id) FROM my_select GROUP BY name)

Is it possible to somehow do the "AS my_select" part (ie assign an alias to a SELECT statement)?是否有可能以某种方式执行“AS my_select”部分(即为 SELECT 语句分配别名)?

(Note: This is a theoretical question. I realize that I can do it without assign an alias to a SELECT statement, but I would like to know whether I can do it with that.) (注意:这是一个理论问题。我意识到我可以在不为 SELECT 语句分配别名的情况下做到这一点,但我想知道我是否可以这样做。)

Not sure exactly what you try to denote with that syntax, but in almost all RDBMS-es you can use a subquery in the FROM clause (sometimes called an "inline-view"):不确定您尝试用该语法表示什么,但在几乎所有 RDBMS-es 中,您都可以在 FROM 子句中使用子查询(有时称为“内联视图”):

SELECT..
FROM (
     SELECT ...
     FROM ...
     ) my_select
WHERE ...

In advanced "enterprise" RDBMS-es (like oracle, SQL Server, postgresql) you can use common table expressions which allows you to refer to a query by name and reuse it even multiple times:在高级“企业”RDBMS-es(如 oracle、SQL Server、postgresql)中,您可以使用通用表表达式,它允许您按名称引用查询并多次重复使用它:

-- Define the CTE expression name and column list.
WITH Sales_CTE (SalesPersonID, SalesOrderID, SalesYear)
AS
-- Define the CTE query.
(
    SELECT SalesPersonID, SalesOrderID, YEAR(OrderDate) AS SalesYear
    FROM Sales.SalesOrderHeader
    WHERE SalesPersonID IS NOT NULL
)
-- Define the outer query referencing the CTE name.
SELECT SalesPersonID, COUNT(SalesOrderID) AS TotalSales, SalesYear
FROM Sales_CTE
GROUP BY SalesYear, SalesPersonID
ORDER BY SalesPersonID, SalesYear;

(example from http://msdn.microsoft.com/en-us/library/ms190766(v=sql.105).aspx ) (示例来自http://msdn.microsoft.com/en-us/library/ms190766(v=sql.105).aspx

You can do this using the WITH clause of the SELECT statement:您可以使用 SELECT 语句的 WITH 子句执行此操作:

;
WITH my_select As (SELECT ... FROM ...) 
SELECT * FROM foo
WHERE id IN (SELECT MAX(id) FROM my_select GROUP BY name)

That's the ANSI/ISO SQL Syntax.这就是 ANSI/ISO SQL 语法。 I know that SQL Server, Oracle and DB2 support it.我知道 SQL Server、Oracle 和 DB2 都支持它。 Not sure about the others...不确定其他人...

Yes, but you can select only one column in your subselect是的,但您只能在子选择中选择一列

SELECT (SELECT id FROM bla) AS my_select FROM bla2

You could store this into a temporary table.您可以将其存储到临时表中。

So instead of doing the CTE/sub query you would use a temp table.因此,您可以使用临时表而不是执行 CTE/sub 查询。

Good article on these here http://codingsight.com/introduction-to-temporary-tables-in-sql-server/关于这些的好文章http://codingsight.com/introduction-to-temporary-tables-in-sql-server/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM