MySQL selects the closest value

I have a table that shows delivery speeds and maximum weight, for example:

max_weight shipping_cost 100 1.50 250 3.00 500 5.00 1000 8.50 30000 12.50 

I want to get the delivery speed depending on the weight of the order, where the weight is less than max_weight in the table. So if the weight is 410, the shipping cost will be 5.00, if the weight is 2000, the delivery is 12.50, etc.

Using max_weight >= '" . $weight . "' Does not work, since it returns only the first max_weight , which is greater than the weight, for example, 683 returns 12.50 as the cost of delivery.

How can I make sure it got the correct max_weight ?

+6
mysql
source share
1 answer

Just use ORDER BY and LIMIT deftly.

  WHERE weight < max_weight ORDER BY max_weight ASC LIMIT 1 
+19
source share

All Articles