SELECT DISTINCT ON表达式必须与初始ORDER BY表达式匹配

Leg*_*ut 0 mysql postgresql activerecord ruby-on-rails

我试图在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)
Run Code Online (Sandbox Code Playgroud)

除了下订单。当我尝试按创建日期排序时:

@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)
Run Code Online (Sandbox Code Playgroud)

我得到错误:

PG::InvalidColumnReference: ERROR:  SELECT DISTINCT ON expressions must match initial ORDER BY expressions
Run Code Online (Sandbox Code Playgroud)

在按创建日期订购时,如何使独特的零件仍可以工作?

Łuk*_*ski 5

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

原始SQL将是:

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

在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)
Run Code Online (Sandbox Code Playgroud)

您可以from() 在此处了解更多信息。我不确定@store.comments语法的含义,因此这可能无法正常工作。