使用mysql查询计算价格

使用mysql查询计算价格,mysql,cart,Mysql,Cart,大师!我被卡住了。目录项的价格取决于其数量。以下是表格示例: items: just item definitions ------------------------- item_id | item_title ------------------------- 1 | "sample item" 2 | "another item" items_prices: prices dependent to item quantity. Les

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

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
是否可以通过单个查询获取当前购物车成本

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

再次加入商品价格可以让我们过滤出任何数量更大但仍符合我们标准的情况。这应该接近我们的目标了

如果
商品价格
最小数量
最大数量
,那就容易多了。哦!在我的例子中,最小数量=数量。是的,我知道了。添加一个
max\u quantity
字段将使您想要的查询非常[相对]容易,尽管它可能会重复数据。(我说“可能”,因为它也会让你选择不允许某些数量值,这可能是有用的。)@Tomalak Geret'kal,我明白了,谢谢!但这会让我今晚死去。每一个新项目的价格记录,我都必须重新计算某些项目的最小|最大数量。现在情况更复杂了。大概可能让我想想:)这两个:
。。。。ip2.quantity>=ip.quantity和ip2.quantity为空
均为真??左join的行为合理,但不是我所期望的。我认为,将条件向上滑动到连接可以清除这种情况;需要去掉限制条件,不再需要按条件排序。我已经验证了这一点,得到了1440,看起来是正确的。
item\u prices
中的单个价格行使您的查询返回空结果。上次你能帮我吗?:)