2014-05-23 33 views
0

我有一個使用基於體重範圍來計算費用見下表了MySQL的費用查詢

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; 

請告訴我設置數據庫的理想方式?

回答

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; 
+0

我懷疑表不是很大,索引可能不是一個大問題。 – Barmar

+0

該表格將少於50個條目,因此根據@Barmar評論 – Carlos

+0

@Carlos索引不會是一個大問題。 。 。可能不會。數據可以放在內存中的單個頁面上,對錶格進行掃描可能就足夠了。也就是說,無論使用哪種結構,在查詢中使'min'成爲主鍵並使用'limit'可能仍然是最優的。 –