2017-08-08 314 views
0

我想基於列是唯一在那裏我得到記錄運行軌道的查詢,在這種情況下,「ACCOUNT_ID」SELECT DISTINCT ON表達式必須初始ORDER BY表達式匹配

這完美的作品:

@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 

如何讓不同的部分,同時通過創建時間排序仍然有效?

回答

3

您需要將其包裝爲子查詢,然後對其進行排序。

原始SQL將是:

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

在軌我覺得這威力工作(使用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語法是什麼意思,所以這可能無法正常工作。