activerecord sql难以查询

时间:2013-11-06 09:20:01

标签: sql ruby-on-rails-3 postgresql activerecord

我需要使用两个选项进行查询:首先 - 选择DISTINCT ON,其次 - 按顺序排序(和其他字段排序)。顺便说一下,不要工作

在一个sql论坛上我找到了解决方案

WITH d AS (
SELECT DISTINCT ON ({Dlist}) {slist}
FROM {flist}
....
)
SELECT * FROM d ORDER BY {order fields}

那么,我如何通过ActiveRecord方法实现这一点并返回ActiveRecord :: Relation

我的完整查询似乎是这样的:

WITH d AS (
SELECT DISTINCT ON(item_info_id, volume) items.item_info_id, items.volume, items.* 
FROM "items" INNER JOIN "item_info" ON "item_info"."id" = "items"."item_info_id" WHERE "items"."type" IN ('Product') 
AND "items"."published" = 't' 
AND ("items"."item_info_id" IS NOT NULL) 
AND ("items"."price" BETWEEN 2 AND 823489)\
)
SELECT * FROM d ORDER_BY 'price'

1 个答案:

答案 0 :(得分:0)

以下可能适合您或给您一些提示

class Item < ActiveRecord::Base
  def self.what_you_want_to_achieve
    item_ids = where("item_info_id IS NOT NULL")
              .select(" DISTINCT on(item_info_id, volume) items.item_info_id, items.volume, items.id ")
              .map(&:id)

    where(:id => item_ids).published.products.price_between(2,823489).order(:price)
  end

我假设您知道如何定义scope,例如published