当我有PG :: UndefinedColumn:ERROR时

时间:2016-05-05 09:32:57

标签: sql ruby-on-rails postgresql activerecord having

我无法理解为什么。 请帮帮我 我有Customer表,有很多订单。所以客户(id),订单(id,customer_id)。我希望得到所有订单少于100的客户。所以我对postgres进行sql查询(我使用Rails和ActiveRecord),但查询是

SELECT customers.*, COUNT(*) AS c_c FROM "customers" LEFT OUTER JOIN orders ON orders.customer_id = customers.id GROUP BY "customers"."id" HAVING c_c < 100 OR orders.id IS NULL

我有错误

ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column "c_c" does not exist

为什么呢?我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

查询本身看起来无效。您不能从HAVING子句引用别名列。你的COUNT(*)也不明确。您可以在c_c中将COUNT(orders.id)替换为HAVING,然后在SELECT中添加COUNT(orders.id)来修复:

SELECT customers.*, COUNT(orders.id) AS c_c FROM "customers" LEFT OUTER JOIN orders ON orders.customer_id = customers.id GROUP BY "customers"."id" HAVING COUNT(orders.id) < 100 OR orders.id IS NULL

修改

对于ActiveRecord查询,请尝试:

Customer.joins("LEFT JOIN orders ON orders.customer_id = customers.id").group("customers.id").having("COUNT(orders.id) < 100")

确保您在has_many :orders

中定义了Customer

答案 1 :(得分:1)

你不能使用c_c

SELECT customers.*, (
  SELECT COUNT(*)
  FROM orders
  WHERE customers.id = orders.customer_id
) AS c_c 
FROM "customers" 
LEFT OUTER JOIN orders 
ON orders.customer_id = customers.id 
GROUP BY "customers"."id" 
HAVING (SELECT COUNT(*)
  FROM orders
  WHERE customers.id = orders.customer_id
) < 100 OR orders.id IS NULL