"TOTAL ON" 用在带括号的连接 SELECT 语句上时实际上有什么作用?

What does "TOTAL ON" when used on a joined SELECT statement with parentheses actually do?

我目前正在学习 SQL Oracle,我的模块中给出的示例之一相当令人费解,主要是因为实际上没有给出任何解释。我确定它是相当基本的,但它使用关键字“TOTAL ON”作为它的一部分,我真的不知道这意味着什么或这个连接实际发生了什么。

我尝试搜索解决方案,但可以理解的是,使用“TOTAL”一词会在 SUM 聚合函数上出现问题。

声明如下:

SELECT CUSTOMER.*, TotalPurchased
FROM CUSTOMER
JOIN
    (
        SELECT CustomerID, SUM(PurchasedAmount) AS TotalPurchased
        FROM PURCHASE
        GROUP BY CustomerID;
    ) TOTAL ON TOTAL.CustomerID = CUSTOMER.CustomerID;

谁能告诉我这是什么?提前谢谢你。

TOTAL 是 sub-query 的别名,ON 是指定 table 连接条件的子句的开头。

您可以将查询重写为:

SELECT table_alias.*,
       subquery_alias.TotalPurchased
FROM   CUSTOMER table_alias
       JOIN (
         SELECT CustomerID, SUM(PurchasedAmount) AS TotalPurchased
         FROM PURCHASE
         GROUP BY CustomerID -- No ; here.
      ) subquery_alias
      ON subquery_alias.CustomerID = table_alias.CustomerID;

I guess the alias then is needed in order to have a name by which to join that subquery?

别名有助于明确哪个列属于哪个table,但在 Oracle 中,如果列是唯一的,则不需要。

注意:一些 RDBMS 要求每个 sub-query 都有一个别名;然而,Oracle 没有。

例如:

SELECT dual.*,
       id
FROM   DUAL
       JOIN ( SELECT DUMMY AS id FROM DUAL )
       ON id = dummy;

输出:

DUMMY ID
X X

因为哪个 table 包含哪一列是明确的。

但使用:

SELECT *
FROM   DUAL
       JOIN DUAL
       ON dummy = dummy;

SELECT *
FROM   DUAL
       JOIN (SELECT DUMMY FROM DUAL)
       ON dummy = dummy;

两者都引发异常:

ORA-00918: column ambiguously defined

由于 ON 子句无法区分 dummy 列指的是哪个 table/sub-query,因为两者使用相同的标识符。

在任何一种情况下,您都可以通过给 sub-query 一个别名(也许 table 一个别名)然后在列标识符前加上 table-name 或别名以澄清哪个是哪个。

db<>fiddle here

TOTAL 只是括号内嵌套 table 的别名。重新格式化一下可能更有意义:

SELECT CUSTOMER.*, TotalPurchased
FROM CUSTOMER
JOIN (
    SELECT CustomerID, SUM(PurchasedAmount) AS TotalPurchased
    FROM PURCHASE
    GROUP BY CustomerID
) AS TOTAL 
  ON TOTAL.CustomerID = CUSTOMER.CustomerID