mysql-更新,多个表联接,从case表达式设置值

时间:2019-07-11 16:53:57

标签: mysql

**下面给出的是更新查询: 表之间的关系:

  • 要订购的card_order-多对一。
  • 订购给客户-一对一。
  • 收费客户-一对多。 设置该值时,即使when子句满足,case表达式也始终求值为表达式的else。请帮助

    update card_orders cbi
        join orders ord on cbi.card_order_no = ord.order_no
        join customers cust on cust.id = ord.customerid 
        join fees fee on fee.customerid = cust.id 
                and active = 1
    set cbi.fee1 =  
        CASE WHEN fee.id = 4 and fee.amount > 0 THEN fee.amount 
        ELSE 'NO FEE' END   
    where cbi.card_order_no = 10250;
    

// fee.amount是mysql的十进制数据类型 设置该值时,即使when子句满足,case表达式也始终求值为表达式的else。  更新还为订单表中的某些列设置了值

更新查询将在存储过程中使用 **

1 个答案:

答案 0 :(得分:0)

使用最后一对多的客户收费服务,您就无法真正控制使用哪个收费记录(UPDATE只更新每个记录一次,因此多个匹配项不会分别更新;即使它们匹配这样,以后的匹配将覆盖以前的更改。

您可以加入费用,添加案件中的条件...

UPDATE card_orders AS cbi
    INNER JOIN orders AS ord ON cbi.card_order_no = ord.order_no
    INNER JOIN customers AS cust ON cust.id = ord.customerid 
    LEFT JOIN fees AS fee1 
            ON fee1.customerid = cust.id AND fee1.active = 1
            AND fee1.id = 4 AND fee1.amount > 0
    LEFT JOIN fees AS feeX 
            ON feeX.customerid = cust.id AND feeX.active = 1
            AND feeX.id = Y AND feeX.amount > 0 
            -- or whatever feeX's case conditions would have been
SET cbi.fee1 = CASE WHEN fee1.customerid IS NOT NULL THEN fee1.amount ELSE 'NO FEE' END
  , cbi.feeX = CASE WHEN feeX.customerid IS NOT NULL THEN feeX.amount ELSE 'NO FEE' END
WHERE cbi.card_order_no = 10250
;

此版本在语义上略有不同。您的原始版本只会更新具有至少一个费用条目链接的card_orders条目;此版本将包含没有任何费用链接的条目。