获得带有折扣的最终价格,但前提是该列不为 NULL。 SQL

Get the final price with discount but only if column is not NULL. SQL

我将这些 sql table 与这些列一起使用:

客户:

id name phone adress etc..
1234 Test Name Test Phone Test Adress etc data.

订单:

customerid orderid orderdate
1234 OR_1234 2022-1-1

orderitems:(在这个table一个客户可以有多行(项目)

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' 

此查询运行良好。但是,如果我想在此查询中添加折扣 table:

怎么办?

折扣:

id name value status
1 Discount 1 valid

所以我想我需要在订单 table 中再创建一列,名称例如:discount_code 如果 discount_code 列不为空,则减去折扣值来自产品价格。

SELECT sum( productprice - discount.value ) as fullprice 但我该如何查询?谢谢你的帮助!

顺便说一句,我使用 MariaDB

祝你有愉快的一天!

如果你只想在你的新列不为空时减去,你可以简单地在你的 SUM() 中使用 IF() func

在非常简单的示例中,假设您添加了 discount_code

create table Orders
(
  id int NOT NULL,
  price int NOT NULL,
  discount_code int NULL  
);

create table Discounts 
(
  id int not null,
  value int not null
);


insert into Orders
values
(1, 10, null),
(2, 10, null),
(3, 5, 1),
(4, 25, 1);


insert into Discounts
values
(1, 3);

select sum(if(o.discount_code is not null, o.price - d.value, o.price))
from Orders as o
left join Discounts as d
on o.discount_code = d.id;

-- 10 + 10 + 2 + 22 = 44

你也可以运行例子here