使用mysql查询计算价格

时间:2011-05-02 22:48:38

标签: mysql cart

大师!我被卡住了。目录项的价格取决于其数量。这里是表格的例子:

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         | 120
2       | 3         | 100

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

单一查询是否有可能获得当前的购物车成本?

1 个答案:

答案 0 :(得分:1)

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

再次返回到items_price,我们可以过滤掉任何数量仍然符合我们标准的情况。这应该接近我们所追求的目标