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

时间:2017-08-08 12:40:52

标签: mysql ruby-on-rails postgresql activerecord

我正在尝试在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

如何在按创建日期排序时让不同的部分仍然有效?

1 个答案:

答案 0 :(得分:3)

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

原始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的经验):

@comments = @store.comments.from(@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)

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