【问题标题】:Get the final price with discount but only if column is not NULL. SQL获得折扣后的最终价格,但前提是列不为 NULL。 SQL
【发布时间】: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

祝你有美好的一天!

【问题讨论】:

    标签: php sql mariadb


    【解决方案1】:

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

    在非常简单的示例中,假设您添加了 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

    【讨论】:

    • 非常感谢!也许这是另一个问题,但是否可以在此查询中检查折扣表中是否存在优惠券?所以它会是:如果不是 null 并且这个 id 存在于 Discounts 表中?再次感谢您!
    • @kviktor1230,也许我误解了你,但查询已经从 Discounts 表中寻找折扣。假设 discount_code 是折扣表(id 字段)的引用键。换句话说,如果 discount_code 为 null,则表示 Discounts 表中没有任何相关行。为简单起见,我只是没有在回答中创建这些关系。
    • 感谢您的回答,今天我尝试了您的查询,但看起来它有问题。所以如果有不止一种产品(客户订购了不止一种产品),那么它就是从产品价格中减去折扣值的倍数。我刚刚创建了一个示例代码:sqlize.online/sql/mariadb/47eeb940dfb322b42e163f5d5a9350c4 谢谢!
    • @kviktor1230,是的,它按预期工作,因为 discount.value 适用于整个订单,如果您希望将该折扣应用于某些特定商品,我建议您在产品中享受折扣表,在您的情况下不在订单表中。
    • @kviktor1230,只需将内连接替换为您的折扣表的左连接,因为 discount_code 可能包含 null。在您的最后一个链接中,您有内部,因此它不会在没有 discount_code 的情况下添加您的订单项,这不是预期的。所以我改变了一点,现在它可以工作了。检查:sqlize.online/sql/mariadb/a6a771303c099020b68da8eaa52f9f86
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多