ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list using order by with uniq

ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list using order by with uniq

我的产品型号有这个范围:

scope :all_products, lambda {
        joins(:prices)
        .where('prices.start_date <= ? and products.available = ?', Time.current, true)
        .uniq
        .order('CASE WHEN products.quantity >= products.min_quantity and (prices.finish_date IS NULL OR prices.finish_date >= now()) THEN 0 ELSE 1 END, prices.finish_date asc')
    }

当我尝试 运行 时出现以下错误:错误:对于 SELECT DISTINCT,ORDER BY 表达式必须出现在 select 列表中

我如何使用我的订单和查询是唯一的?我用 rails 4.

  1. 您需要先 select 列,以便稍后在 .order
  2. 中订购它们
  3. 尽管使用 .uniq.distinct 结果仍然会有重复的记录,因为生成的查询是 SELECT DISTINCT products.*, prices.finish_date, ... 试图找到 products.*, prices.finish_date and the special column 的所有组合具有唯一值(在这种情况下,您只希望 products.id 是唯一的)

DISTINCT ON 是解决方案,但由于 SELECT DISTINCT ON expressions must match initial ORDER BY expressionspostgres 使用它有点棘手。

请尝试:

sub_query = Product.joins(:prices)
  .select("DISTINCT ON (products.id) products.*, CASE WHEN (products.quantity >= products.min_quantity) AND (prices.finish_date IS NULL OR prices.finish_date >= now()) THEN 0 ELSE 1 END AS t, prices.finish_date AS date")

query = Product.from("(#{sub_query.to_sql}) as tmp").select("tmp.*").order("tmp.t, tmp.date ASC")