【发布时间】:2022-01-11 16:32:41
【问题描述】:
我将这些 sql 表与这些列一起使用:
客户:
| id | name | phone | adress | etc.. |
|---|---|---|---|---|
| 1234 | Test Name | Test Phone | Test Adress | etc data. |
订单:
| customerid | orderid | orderdate |
|---|---|---|
| 1234 | OR_1234 | 2022-1-1 |
orderitems:(在此表中,一个客户可以有多个行(items)
| id | orderid | productid |
|---|---|---|
| 1 | OR_1234 | P1 |
产品:
| productid | productprice | currency | qty | name | weight |
|---|---|---|---|---|---|
| P1 | 10 | USD | 1 | TEST | 0.2 KG |
所以在这种情况下,如果我想从客户的订单中获取全价,我会使用以下查询:
SELECT sum( productprice ) as fullprice
FROM customers
inner join orders on orders.customerid = customers.id
inner join orderitems on orderitems.orderid = orders.orderid
inner join products on products.productid = orderitems.productid
WHERE customers.id = '1234'
此查询运行良好。但是如果我想在这个查询中添加折扣表中的折扣怎么办:
折扣:
| id | name | value | status |
|---|---|---|---|
| 1 | Discount | 1 | valid |
所以我想我需要在订单表中再创建一列,例如:discount_code,如果 discount_code 列不为空,则从 productprice 中减去折扣值。
SELECT sum( productprice - discount.value ) as fullprice 但如何进行此查询?谢谢你的帮助!
顺便说一句,我使用 MariaDB
祝你有美好的一天!
【问题讨论】: