【问题标题】:ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list using order by with uniq错误:对于 SELECT DISTINCT,ORDER BY 表达式必须使用 order by 和 uniq 出现在选择列表中
【发布时间】:2019-12-24 02:45:19
【问题描述】:

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

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 表达式必须出现在选择列表中

我如何使用我的 order by 并且查询是唯一的?我使用 Rails 4。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 activerecord


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

    DISTINCT ON 是解决方案,但对于 postgres 来说使用它有点棘手,因为 SELECT DISTINCT ON expressions must match initial ORDER BY expressions

    请尝试:

    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")
    

    【讨论】:

    • 它可以工作...但我的查询结果中仍然有重复的产品。 uniq 不起作用。
    • @denispolicarpocampos,抱歉,它应该是 .distinct 而不是 .uniq。更新答案
    • 与 .distinct 我有相同的副本...这很奇怪...
    • @denispolicarpocampos,您面临的问题与stackoverflow.com/questions/32775220/… 几乎相同。 .distinct.uniq 仍然会输出重复的记录,因为生成的查询会尝试查找所有尝试查找具有唯一值的 products.*, prices.finish_date and the special column 的所有组合,但我们只希望 products.id 是唯一的。我已经根据那篇帖子更新了我的答案。
    猜你喜欢
    • 2023-03-23
    • 2012-09-23
    • 2020-10-12
    • 2018-01-16
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多