我有一個很長的關聯鏈,連接,排序等,最終從我的一個rails模型中進行選擇。在一天結束時,我需要結果是獨特的和排序的。我不在乎SELECT語句中使用了哪些列,ORDER BY中出現了什麼(這些都是基於用戶選擇的過濾選項而改變的),我只關心頂層模型/表格查詢是唯一的(基於id)。PG :: InvalidColumnReference:錯誤:對於SELECT DISTINCT,ORDER BY表達式必須出現在選擇列表中
有關背景,widgets
是主表,我們正在與widget_steps
的加盟,這是Rails 3的(公司正在努力盡快升級,但是這就是他們堅持的時刻是什麼)
這裏是正在生成的查詢和錯誤:
PG::InvalidColumnReference: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
LINE 1: ...completed_at" IS NULL)) ORDER BY sequential DESC, widget_s...
^
: SELECT DISTINCT "widgets".* FROM "widgets" INNER JOIN "widget_steps" ON "widget_steps"."widget_id" = "widgets"."id" INNER JOIN "widget_steps" "active_steps_widgets" ON "active_steps_widgets"."id" = "widgets"."active_widget_step_id" WHERE "widgets"."account_id" = 1 AND "widgets"."completed_at" IS NULL AND (("widgets"."sequential" = 't' AND "widget_steps"."assigned_to" = 5 AND "widget_steps"."id" = "widgets"."active_widget_step_id" AND "widget_steps"."completed_at" IS NULL) OR ("widgets"."sequential" = 'f' AND "widget_steps"."assigned_to" = 5 AND "widget_steps"."completed_at" IS NULL)) ORDER BY sequential DESC, widget_steps.name ASC LIMIT 10 OFFSET 0
Completed 500 Internal Server Error in 52.3ms
ActiveRecord::StatementInvalid - PG::InvalidColumnReference: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
LINE 1: ...completed_at" IS NULL)) ORDER BY sequential DESC, widget_s...
^
: SELECT DISTINCT "widgets".* FROM "widgets" INNER JOIN "widget_steps" ON "widget_steps"."widget_id" = "widgets"."id" INNER JOIN "widget_steps" "active_steps_widgets" ON "active_steps_widgets"."id" = "widgets"."active_widget_step_id" WHERE "widgets"."account_id" = 1 AND "widgets"."completed_at" IS NULL AND (("widgets"."sequential" = 't' AND "widget_steps"."assigned_to" = 5 AND "widget_steps"."id" = "widgets"."active_widget_step_id" AND "widget_steps"."completed_at" IS NULL) OR ("widgets"."sequential" = 'f' AND "widget_steps"."assigned_to" = 5 AND "widget_steps"."completed_at" IS NULL)) ORDER BY sequential DESC, widget_steps.name ASC LIMIT 10 OFFSET 0:
這是爲什麼? postgres認爲對此如此含糊不清?爲什麼像這樣的查詢在MySQL中總能正常工作,但會導致postgres窒息。
我曾嘗試:
- 在鏈
- 指定
.uniq
在鏈的末端沒有做一個自定義的結束指定.select([everything mentioned in the order by]).uniq
選擇 - 編寫一些自定義的AREL嘗試嵌入所有這在子查詢中,然後執行.uniq或.order以外的這個(不能得到這個工作)
- 做postgres之外的.uniq(這是因爲分頁而中斷...你可以最終一些頁面只有1個或者被刪除2項,因爲重複的對他們)
- 哭
什麼是'順序'在這裏?是某個桌子或其他東西的列嗎? –
它是一個小工具欄 –
想一想:當存在(至少)兩行'widget_steps'時,它滿足了你單個行的'widget'的條件,哪個'name'應該用在' ORDER BY'? PostgreSQL不會決定這個,而不是你,這就是爲什麼它說把'widget_steps.name'放入'SELECT'子句(以使這個也是'DISTINCT')。 OFC,MySQL不會用這樣的無稽之談:它允許你運行你想出的任何錯誤的查詢。 – pozs