开发者

Calculate price with mysql query

开发者 https://www.devze.com 2023-03-02 14:57 出处:网络
gurus! I am stuck. Catalog items have prices dependent to its quantity. Here example of tables: items: just item definitions

gurus! I am stuck. Catalog items have prices dependent to its quantity. Here example of tables:

items: just item definitions
-------------------------
item_id | item_title
-------------------------
1       | "sample item"
2       | "another item"

items_prices: prices dependent to item quantity. 
              Less price taken for more quantity of item
----------------------------
item_id | quantity  | price
----------------------------
1       | 1         | 100
1       | 5         | 80
1       | 10        | 60
2       | 1         | 开发者_如何学Go120
2       | 3         | 100

cart
-------------------
item_id | quantity  
-------------------
1       | 20
2       | 2

Is it possible to get current cart cost with single query?


select sum(x.totalcost)
from (
    select c.item_id, c.quantity * ip.price as totalcost
    from cart c
    join items_prices ip
      on c.item_id = ip.item_id
    left join items_prices ip2
      on ip2.quantity > ip.quantity
      and c.quantity >= ip2.quantity
    where c.quantity >= ip.quantity
      and ip2.quantity is null
) x

The join back onto items_price again lets us filter out any cases where there is a greater quantity which still meets our criteria. This should be getting close to what we're after

0

精彩评论

暂无评论...
验证码 换一张
取 消