Mysql2错误 - 在where子句中使用COALESCE,Unknown列

时间:2018-02-07 06:07:17

标签: mysql ruby-on-rails activerecord

在我的Rails 4.1应用程序中,我构建一个查询,通过多态关系(买方)的属性(名称)查找我的集合(订单)中的记录。这个多态有2个可能的表,所以我使用2 LEFT JOINS + COALESCE来合并属性。然后尝试在where子句中使用COALESCE中的值。

我的ActiveRecord模型中的方法如下所示:

class Order
  ...
  scope :join_by_buyer_name, -> { select("stock_orders.*", "COALESCE(core_customers.business_name, core_entities.name) AS buyer_name")
      .joins("LEFT JOIN core_customers ON stock_orders.buyer_id = core_customers.id AND stock_orders.buyer_type='Core::Customer'")
      .joins("LEFT JOIN core_entities ON stock_orders.buyer_id = core_entities.id AND stock_orders.buyer_type='Core::Entity'")
    }
  ...

  def find_by_buyer_name(term)
    all.join_by_buyer_name.where("buyer_name LIKE ?", term)
  end


end

执行ActiveRecord查询时,它看起来像这样

SELECT stock_orders.*, COALESCE(core_customers.business_name, core_entities.name) AS buyer_name
FROM `stock_orders`
LEFT JOIN core_customers ON stock_orders.buyer_id = core_customers.id AND stock_orders.buyer_type='Core::Customer'
LEFT JOIN core_entities ON stock_orders.buyer_id = core_entities.id AND stock_orders.buyer_type='Core::Entity'
WHERE `stock_orders`.`type` IN ('Stock::SalesOrder') AND (buyer_name LIKE "blah")

直到最近这个工作,但我已经开始收到以下错误:

Mysql2::Error: Unknown column 'buyer_name' in 'where clause': SELECT stock_orders.*, COALESCE等等

它非常适合按COALESCE值排序 - 即collection.order("buyer_name asc"),直到最近查询工作完全正确...

我不确定发生了什么变化,并且无法在Rails或Mysql文档中看到任何内容。你能看出这里有什么问题吗?请帮忙!

1 个答案:

答案 0 :(得分:0)

您不能使用从ALIAS子句创建的WHERE子句中的SELECT。请改用计算列,

AND (COALESCE(core_customers.business_name, core_entities.name) LIKE "blah")

如果你想使用ALIAS,你必须将它包装在子查询中,如下面的查询,

SELECT *
FROM
     (
     SELECT stock_orders.*, 
           COALESCE(core_customers.business_name, core_entities.name) AS buyer_name
     FROM `stock_orders`
          LEFT JOIN core_customers 
                ON stock_orders.buyer_id = core_customers.id 
                     AND stock_orders.buyer_type='Core::Customer'
          LEFT JOIN core_entities 
                     ON stock_orders.buyer_id = core_entities.id 
                     AND stock_orders.buyer_type='Core::Entity'
     ) subquery
WHERE `type` IN ('Stock::SalesOrder') 
      AND (buyer_name LIKE "blah")