【问题标题】:How to select unique records based on foreign key column in Rails?如何根据Rails中的外键列选择唯一记录?
【发布时间】:2014-10-19 07:52:38
【问题描述】:

我的 Rails 4.1 应用程序中有以下模型结构:

delivery_service.rb

class DeliveryService < ActiveRecord::Base
    attr_accessible :name, :description, :courier_name, :active, :country_ids

    has_many :prices, class_name: 'DeliveryServicePrice', dependent: :delete_all
end

delivery_service_price.rb

class DeliveryServicePrice < ActiveRecord::Base

  attr_accessible :code, :price, :description, :min_weight, :max_weight, :min_length, :max_length, 
  :min_thickness, :max_thickness, :active, :delivery_service_id

  belongs_to :delivery_service
end

如您所见,送货服务有很多送货服务价格。我正在尝试从送货服务价格表中检索记录; 在外键的唯一范围内选择具有最低价格属性的记录,delivery_service_id(因此本质上是每个送货服务最便宜的送货服务价格)。

如何从表中选择唯一记录,以外键属性为范围?

我希望我已经解释得够多了,如果您需要更多信息,请告诉我。

谢谢

更新 #1:

我想要实现的示例:

delivery_service_prices 表:

id:1,价格:2.20,delivery_service_id:1

id:2,价格:10.58,delivery_service_id:1

id:3,价格:4.88,delivery_service_id:2

id:4,价格:1.20,delivery_service_id:2

id:5,价格:14.99,delivery_service_id:3

预期结果:

id:1,价格:2.20,delivery_service_id:1

id:4,价格:1.20,delivery_service_id:2

id:5,价格:14.99,delivery_service_id:3

【问题讨论】:

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


    【解决方案1】:

    由于 PostgreSQL 在遵守 SQL 标准方面更加严格(这是正确的),因此需要进行一些调整才能获得正确的结果。

    以下查询返回每个送货服务最低送货服务价格的正确结果:

    DeliveryServicePrice.select('DISTINCT ON (delivery_service_id) *').order('delivery_service_id, price ASC')
    

    我需要在订单条件中添加delivery_service_id属性,否则PostgreSQL会抛出以下列错误:

    PG::InvalidColumnReference: ERROR:  SELECT DISTINCT ON expressions must match initial ORDER BY expressions
    

    希望这可以帮助任何偶然发现它的人!

    【讨论】:

      【解决方案2】:

      要获得单个记录的最小值,您可以使用

      DeliveryServicePrice.where(delivery_service_id: x).order(:price).limit(1).first
      

      或者如果您有可用的delivery_service 对象

      delivery_service.prices.order(:price).limit(1).first
      

      更新

      如果您想要所有service_delivery_ids 的所有最小值,您可以使用group 查询

      DeliveryServicePrice.group(:delivery_service_id).minimum(:price)
      

      这会让你几乎到达你想去的地方

      {
        1: 2.20,
        2: 1.20,
        3: 14.99
      }
      

      带有包含delivery_service_id 和价格的散列。 (你看不到 price_id )

      【讨论】:

      • 感谢您的回复。我不是要从一项送货服务中检索送货服务价格,我需要从所有送货服务中选择最低价格的送货服务价格。
      • 上面的查询仍然需要传递服务ID参数where(delivery_service_id: x)。我想选择外键属性delivery_service_id的唯一范围内的最低价格配送服务价格。
      • 您希望查询返回所有 delivery_services 的最低价格吗? (每个 _id 的最小值)?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-06
      • 2023-01-18
      • 1970-01-01
      相关资源
      最近更新 更多