0

我需要使用两个选项进行查询:首先 - 选择 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'
4

1 回答 1

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

于 2013-11-06T10:28:32.910 回答