我有這樣的ActiveRecord查詢:如何使用Postgresql統計Rails 4中的不同查詢?
Stock.select('DISTINCT ON (stocks.part_number)*').joins(:part, :manufacturer)
.includes(:manufacturer, :part).order(:part_number).with_cat(category).
where(manufacturers: {abbr: ['manufacturer1', 'manufacturer2']})
with_cat
是一個範圍:
scope :with_cat, -> (category) { where(parts: {category_id: category}) }
我現在用Distinct on
的原因是因爲每個製造商都可以有相同的部分,另一種,因此重複。我不想重複。上面的工作完成了。除了當我添加count
它時,我收到一個錯誤。
PG::SyntaxError: ERROR: syntax error at or near "ON"
LINE 1: SELECT COUNT(DISTINCT ON (stocks.part_number)*) FROM "stocks...
^
: SELECT COUNT(DISTINCT ON (stocks.part_number)*) FROM "stocks"
INNER JOIN "parts" ON "parts"."id" = "stocks"."part_id"
INNER JOIN "manufacturers" ON "manufacturers"."id" = "stocks"."manufacturer_id"
WHERE "parts"."category_id" = 17 AND "manufacturers"."abbr" IN ('manufacturer1', 'manufacturer2')
不確定如何向查詢添加計數而不會導致該錯誤。我也不熟悉Distinct on
。爲什麼會發生這種情況的任何解釋都會很棒!
您還可以顯示當您*不*使用'count'時生成的SQL查詢嗎? – jeffdill2
@ jeffdill2它與count的結果查詢相同,但減去'count'及其包含的parens。我可以添加它,但其中只有幾個字符可以刪除,而我目前不在我的編輯器前面。 – Andy