我有下表用于根据重量范围计算费用
Charge Weight
1 0.5
2 1
3 2
4 5
我想计算一个重2.5的盒子的费用,
select charge from charge_table where weight > 2.5 limit 1;
或者应该使用此选项,但它会复制数据吗?
Charge min max
1 0 0.5
2 0.5 1
3 1 2
4 2 5
然后使用以下查询
select * from charge_table where min > 2.5 and max <= 2.5;
什么是设置数据库的理想方式?
答案 0 :(得分:1)
考虑第一种方法。正确的查询是:
select charge
from charge_table
where weight > 2.5
order by weight desc
limit 1;
您需要charge_table(weight, charge)
上的索引。智能使用索引将是查找值2.5
,然后找到它旁边的第一个值。
使用第二种方法,您的查询是正确的。它可以使用min
/ max
上的索引。但是,由于不平等,索引使用可能效率不高。为了获得相同的效率,您可以:
select *
from charge_table
where min > 2.5 and max <= 2.5
limit 1;