我可以使用带有子查询的SQL COUNT找到至少有5个订单的客户总数:
SELECT COUNT(*) FROM (
SELECT c.id FROM customers as c
INNER JOIN orders as o ON c.id = o.customer_id
GROUP BY c.id
HAVING COUNT(o.id) >= 5
) as temp
但是,如果可能的话,我想知道如何使用Rails活动记录查询接口实现相同的功能。
我有代码:
total_count = Customer.joins("INNER JOIN orders ON customers.id = orders.customer_id").group("customers.id").having("COUNT(orders.id) >= 5").count
但是这导致了客户ID和订单数量的哈希映射,因为生成的SQL看起来像:
SELECT COUNT(*) AS count_all, customers.id AS customers_id FROM `customers` INNER JOIN orders ON customers.id = orders.customer_id GROUP BY customers.id HAVING COUNT(orders.id) >= 5
有没有其他方法可以实现我的目标是使用Rails约定?或者我应该只构建原始查询?
答案 0 :(得分:0)
如果您想要来自客户的其他信息,例如他们的姓名或类似信息,您需要加入。如果count是你想要的只是在订单表上做一个简单的查询:
SELECT * FROM orders
GROUP BY customer_id
HAVING COUNT(customer_id) >= 5
并计算结果集中的行数。