在连接中使用Where子句,使用Group by和Order By

时间:2012-05-12 02:16:21

标签: mysql sql join left-join

我正在使用MySQL classicmodels数据库。以下查询工作正常(请注意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。无效使用群组功能

5 个答案:

答案 0 :(得分:9)

聚合函数(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

答案 1 :(得分: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

答案 2 :(得分: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

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

希望有所帮助

答案 3 :(得分:0)

请试试这个

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

答案 4 :(得分:0)

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

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

enter image description here