当尝试在FROM子句中运行嵌套子查询时,我偶然发现了MySQL(v.8)的奇怪行为。我正在使用的示例数据库的(相关部分)架构如下:
以下两个查询在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'
我会感激有关为什么发生这种情况的任何线索。 请注意,我最感兴趣的不是解决此查询的方法或其他方法,而是了解嵌套查询失败的原因。
答案 0 :(得分:1)
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
答案 1 :(得分:1)
您可以尝试以下操作
SELECT
(
select SUM(tot) as total from
(
SELECT
(
SELECT SUM(OD.quantityOrdered * OD.priceEach)
FROM orderdetails OD
WHERE OD.orderNumber = O.orderNumber
) AS tot,customerNumber
FROM orders O
) as ord
WHERE ord.customerNumber = C.customerNumber
) AS total
FROM customers AS C;
您的客户表不在条件WHERE O.customerNumber = C.customerNumber
中使用的子查询范围内,因此我为此设置了别名
然后在更高级别上,我使用相同的条件,其中客户表具有范围
答案 2 :(得分:1)
在第二种情况下,您具有相关的子查询。但是,相关子句的深度为两个级别。
即使嵌套多个级别,许多数据库仍然可以识别c
。但是,MySQL(以及Oracle和我认为MS Access)是一个将关联子句限制在一个层次上的数据库。