在Rails 7.0中如何根据数量查询products表对应价格?
根据数量查询对应商品价格
环境信息
- Rails版本:
7.0 - PostgreSQL版本:
14
问题描述
如何根据给定数量查询products表中对应的价格?
表结构
min_quantity | max_quantity | price 1 | 4 | 200 5 | 9 | 185 10 | 24 | 175 25 | 34 | 150 35 | 999 | 100 1000 | null | 60
预期结果
3 ===> 200 50 ===> 100 2500 ===> 60
解决方案
1. 原生SQL查询
直接通过PostgreSQL语句匹配数量所在区间,重点处理max_quantity为null的无上限场景:
SELECT price FROM products WHERE min_quantity <= [给定数量] AND (max_quantity IS NULL OR max_quantity >= [给定数量]);
示例(查询数量为50的价格):
SELECT price FROM products WHERE min_quantity <= 50 AND (max_quantity IS NULL OR max_quantity >= 50);
2. Rails ActiveRecord实现
在Product模型中封装查询逻辑,方便业务调用:
# app/models/product.rb class Product < ApplicationRecord def self.price_for(quantity) where('min_quantity <= ?', quantity) .where('max_quantity IS NULL OR max_quantity >= ?', quantity) .pluck(:price) .first end end
调用示例:
Product.price_for(3) # 返回200 Product.price_for(50) # 返回100 Product.price_for(2500) # 返回60
说明
由于表中数量区间连续且无重叠,上述查询只会返回唯一匹配的价格,直接取第一条结果即可。max_quantity为null的行专门匹配大于等于1000的数量。
内容的提问来源于stack exchange,提问作者Remy Wang
相关产品推荐
相关产品推荐

