解决MySQL Complex父子查询问题

时间:2015-08-13 03:39:49

标签: mysql sql

我有两个表:order和orderitem,结构如下:

order
[order_ID (primary)][base_price][discount][final_price]

orderitem
[item_ID (primary)][order_ID (primary)][price][color]

Note: one order can have many orderitem ( one to many )

让我们假设我们有以下样本数据:

order
-------------------------------
[1] [100] [10] [90]
[2] [200] [10] [190]

orderitem
-------------------------------
[A] [1] [25] [blue]
[B] [1] [25] [blue]
[C] [1] [25] [blue]
[D] [1] [25] [red]

[E] [2] [100] [blue]
[F] [2] [100] [red]

我们从orderitem总价中获得了order.base_price:

order.base_price = SUM(orderitem.price) WHERE orderitem.order_ID = order.order_ID

然后我们根据需要应用折扣,因此:

order.final_price = order.base_price - order.discount

到目前为止一切顺利。正如您所看到的,我对order_ID 1应用了10%的折扣,对order_ID 2应用了5%的折扣。问题是我只想计算红色的订单最终价格的总和,但我不知道如何在一个查询中做到这一点。如果没有应用折扣,那么我可以这样做:

SELECT SUM(orderitem.price) WHERE orderitem.color='red'

但由于我们在这里有折扣,理想情况下我想根据每个订单的折扣百分比扣除个别商品。逻辑如下:

第1步 - 获取每个订单的折扣百分比

percent = order.discount / order.base_price * 100
order_ID = 1 --> percent = [10] / [100] * 100 = 10%
order_ID = 2 --> percent = [10] / [200] * 100 =  5%

第2步 - 根据订单百分比

扣除所有红色订购项目
orderitem = D-1 --> deducted = 25 - 10% = 22.5
orderitem = F-2 --> deducted = 100 - 5% = 95

第3步 - 计算红色所有扣除值的总和

SELECT SUM(deducted) FROM orderitem WHERE orderitem.color = 'red'

Expected result = 22.5 + 95 = 117.5

如何在单个SQL查询中执行此操作?我希望有人可以解释一下......

1 个答案:

答案 0 :(得分:0)

我使它更通用所以显示所有颜色总数。

您可以添加where color = 'red'代替GROUP BY color;

SQLFIDDLE DEMO

SELECT color, SUM(price*discount) as total_discount
FROM 
    orderitem o
INNER JOIN
    (SELECT order_ID, final_price / base_price as discount
    FROM orders) d
ON o.order_ID = d.order_ID
GROUP BY color;