使用mysql查询计算价格

发布于 2024-11-04 07:42:09 字数 660 浏览 0 评论 0原文

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

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

是否可以通过单个查询获取当前的购物车成本?

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如若梦似彩虹 2024-11-11 07:42:09
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 可以让我们过滤掉任何数量较多但仍符合我们标准的情况。这应该接近我们想要的

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文