我正在尝试在 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
如何让不同的部分在按创建日期订购时仍然有效?
最佳答案
您需要将其包装为子查询,然后对其进行排序。
原始 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
语法是什么意思,所以这可能行不通。
关于mysql - SELECT DISTINCT ON 表达式必须匹配初始 ORDER BY 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45568663/