MySQL查询查找订单最多的客户

时间:2010-03-15 15:29:15

标签: sql mysql

tbl_customer.id是客户的ID

tbl_order.customer_id

一个查询,它将选择tbl_order

中包含4个或更多记录的所有客户

3 个答案:

答案 0 :(得分:3)

SELECT tbl_order.customer_id, COUNT(*)
    FROM tbl_order 
    GROUP BY customer_id 
    HAVING COUNT(*) > 4

答案 1 :(得分:1)

select customer.id, count(*) as num_orders
from customer
inner join tbl_order ON (tbl_order.customer_id = customer.id)
group by customer.id
having num_orders >= 4;

答案 2 :(得分:0)

使用上述答案的组合(谢谢)

我最终得到了什么

SELECT c.first_name,c.SURNAME,c.ADDRESS1,c.CREATED ,COUNT(*) AS num_orders 
FROM tbl_customer AS c
INNER JOIN tbl_order_head AS o ON (o.customer_id = c.id) 
GROUP BY c.id 
HAVING num_orders >= 4 ORDER BY num_orders DESC;