【问题标题】:SELECT DISTINCT ON expressions must match initial ORDER BY expressionsSELECT DISTINCT ON 表达式必须匹配初始 ORDER BY 表达式
【发布时间】:2018-01-16 01:03:09
【问题描述】:

我正在尝试在 Rails 中运行查询,在该查询中我根据唯一的列获取记录,在本例中为“account_id”

这很好用:

@comments = @store.comments.where(account_id: @selected_array).where(flagged: true).select('distinct on (account_id) *').paginate(:page => params[:page], :per_page => 30)

除非订单已关闭。当我尝试按创建日期订购时:

@comments = @store.comments.where(account_id: @selected_array).where(flagged: true).select('distinct on (account_id) *').order("created_at DESC").paginate(:page => params[:page], :per_page => 30)

我得到错误:

PG::InvalidColumnReference: ERROR:  SELECT DISTINCT ON expressions must match initial ORDER BY expressions

在按创建日期订购时,如何使不同部分仍然有效?

【问题讨论】:

    标签: mysql ruby-on-rails postgresql activerecord


    【解决方案1】:

    您需要将其包装为子查询,然后对其进行排序。

    原始 SQL 将是:

    SELECT * FROM (
      SELECT DISTINCT ON (account) * FROM comments WHERE account_id = 5 AND flagged
    ) AS sub
    ORDER BY created_at DESC
    

    在 Rails 中,我认为这可能有效(没有使用 Ruby 或 ActiveRecord 的经验):

    store_comments = @store.comments
    @comments = store_comments.from(store_comments
                                    where(account_id: @selected_array, flagged: true).
                                    select('distinct on (account_id) *'))
                              .order(:created_at)
                              .paginate(page: params[:page], per_page: 30)
    

    您可以阅读更多关于 from() here 的信息。我不确定@store.comments 语法是什么意思,所以这可能行不通。

    【讨论】:

      猜你喜欢
      • 2018-11-06
      • 1970-01-01
      • 2012-09-23
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-12
      • 1970-01-01
      相关资源
      最近更新 更多