views:

36

answers:

2
+5  Q: 

MySQL query help

Hi All,

Need a help in building query. I have quantity_price table, listing quantity and corresponding price as shown below

Quantity  Price
----------------
1   --  € 175,35
2.5 --  € 160,65
5   --  € 149,10
10  --  € 143,85

so for upto 1 quantity price will be 175,35 up to 2.5 it will be 160,65 and so on. For more than 10 quantity, price'll remain to 143,85.

Now if my quantity is 1.5 then query should return price 160,65, which means that find in which range quantity resides and then get the price of max quantity in the range.

+1  A: 

Use a where statement to find all rows bigger than 1.5; then use limit and order by to grab the row with the lowest quantity. As Petah commented, it's handy to always include the row with the largest quantity. For example:

select  *
from    quantity_price
where   Quantity > 1.5
        or Quantity = (select max(Quantity) from quantity_price)
order by
        Quantity
limit   1
Andomar
This fails if the quantity if more than 10
Petah
@Petah: Good point, query edited!
Andomar
+2  A: 
select price
from quantity_price
where myquantity >= quantity
order by quantity
limit 1
Faisal Feroz
Shouldn't this be `order by quantity ASC` ?
Andomar
yes, query edited.
Faisal Feroz
shoudn't this be `<=` (or `quantity >= myquantity`) ... and it doesn't work for `myquantity` over 10 ?
richaux