6

我正在使用 MySQL 经典模型数据库。以下查询工作正常(注意 where 子句)

select 
    customers.customerNumber as 'Customer ID',
    customers.customerName as 'Customer Name',
    count(orders.orderNumber) as 'Total Orders Placed'
from customers
left join orders on customers.customerNumber = orders.customerNumber
where customers.customerNumber > 200
group by
    customers.customerNumber
order by 
    3 asc

但是以下会导致错误。目的是仅在结果行集中显示那些下达 3 个以上订单的客户。我究竟做错了什么?

select 
    customers.customerNumber as 'Customer ID',
    customers.customerName as 'Customer Name',
    count(orders.orderNumber) as 'Total Orders Placed'
from customers
left join orders on customers.customerNumber = orders.customerNumber
where count(orders.orderNumber) > 3
group by
    customers.customerNumber
order by 
    3 asc

MySQL错误是:错误代码:1111。组函数的使用无效

4

5 回答 5

11

聚合函数(COUNT(), AVG(), SUM(),等)不能出现在WHERE子句中,因为它们是计算的。相反,它们属于一个HAVING子句:

select 
    customers.customerNumber as 'Customer ID',
    customers.customerName as 'Customer Name',
    count(orders.orderNumber) as 'Total Orders Placed'
from customers
left join orders on customers.customerNumber = orders.customerNumber
group by
    customers.customerNumber
HAVING count(orders.orderNumber) > 3
order by 
    3 asc
于 2012-05-12T02:19:12.787 回答
1

一种更有效的方法是通过聚合将组移动到嵌套派生表中并加入该表。

SELECT 
  c.customerNumber AS 'Customer ID',
  c.customerName AS 'Customer Name',
  o.orderCount AS 'Total Orders Placed'
FROM 
  customers c
LEFT JOIN
  (SELECT
     customerNumber, 
     COUNT(*) AS orderCount
   FROM
     orders
   GROUP BY
     customerNumber) o
 ON
   c.customerNumber = o.customerNumber
 WHERE
   o.orderCount > 3
 ORDER BY
   3
于 2012-05-12T03:04:47.520 回答
1

在 where 子句中有一种间接使用聚合函数的方法

您可以将查询重写为


select customers.customerNumber as 'Customer ID',
       customers.customerName as 'Customer Name',
       count(orders.orderNumber) as 'Total Orders Placed'
  from customers left join orders on customers.customerNumber =
                                     orders.customerNumber
 where
 (SELECT CASE
        WHEN count(orders.orderNumber) > 3 THEN
             'TRUE'
        ELSE
             'FALSE'
        END
   FROM DUAL) = 'TRUE'
 group by customers.customerNumber
 order by 3 asc

这里,在 select 子句中使用了 count 函数,它根据 count 计算返回 FALSE 字符串的 TRUE。

希望能帮助到你

于 2012-05-12T03:25:20.373 回答
1

请试试这个

select 
  customers.customerNumber as 'Customer ID',
  customers.customerName as 'Customer Name',
  count(orders.orderNumber) as 'Total Orders Placed'
from customers
inner join orders on customers.customerNumber = orders.customerNumber
group by
  customers.customerNumber, 
  customers.customerName
having count(orders.orderNumber) > 3
order by 
  3 asc
于 2012-05-12T08:56:09.723 回答
0

这是您要实现的目标的简化版本。

SELECT 
    customers.customerName,
    COUNT(orders.orderNumber) totalOrders
FROM
    customers
        JOIN
    orders ON customers.customerNumber = orders.customerNumber
GROUP BY customers.customerName
HAVING totalOrders > 2;

在此处输入图像描述

于 2021-04-28T17:09:13.527 回答