gpt4 book ai didi

mysql - FROM 子句中的子查询在 MySQL 中失败

转载 作者:太空宇宙 更新时间:2023-11-03 11:27:26 25 4
gpt4 key购买 nike

尝试在 FROM 子句中运行嵌套子查询时,我偶然发现了 MySQL (v.8) 的一个奇怪行为。我正在使用的示例数据库的(相关部分)架构如下:

enter image description here

以下两个查询在 SQL Server 上运行相同:

SELECT SUM(tot) as total
FROM (
SELECT
SUM(OD.quantityOrdered * OD.priceEach) as tot,
C.customerNumber
FROM customers C
INNER JOIN orders O ON C.customerNumber = O.customerNumber
INNER JOIN orderdetails OD ON O.orderNumber = OD.orderNumber
GROUP BY O.orderNumber, C.customerNumber
) AS CO
GROUP BY CO.customerNumber;

SELECT 
(
SELECT SUM(tot) as total
FROM
(
SELECT
(
SELECT SUM(OD.quantityOrdered * OD.priceEach)
FROM orderdetails OD
WHERE OD.orderNumber = O.orderNumber
) AS tot
FROM orders O
WHERE O.customerNumber = C.customerNumber
) AS ORD
) AS total
FROM customers AS C;

然而,在 MySQL 上,第一个运行良好,而第二个导致错误:

Error Code: 1054. Unknown column 'C.customerNumber' in 'where clause'

我将不胜感激关于为什么会发生这种情况的任何线索。 请注意,我最感兴趣的不是解决方法或其他实现此查询的方法,而是了解嵌套查询失败的原因。

最佳答案

C 表别名不在 suquery 范围内
尝试使用连接重构查询

例如

select  c.customerNumber,  t.my_tot 
FROM customers AS C
INNER JOIN (

SELECT O.customerNumber, SUM(OD.quantityOrdered * OD.priceEach) my_tot
FROM orderdetails OD
INNER JOIN orders O ON OD.orderNumber = O.orderNumber
GROUP BY O.customerNumber
) t on t.customerNumber = c.customerNumber

select  t.my_tot 
FROM customers AS C
INNER JOIN (

SELECT O.customerNumber, SUM(OD.quantityOrdered * OD.priceEach) my_tot
FROM orderdetails OD
INNER JOIN orders O ON OD.orderNumber = O.orderNumber
GROUP BY O.customerNumber
) t on t.customerNumber = c.customerNumber

关于mysql - FROM 子句中的子查询在 MySQL 中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53187525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com