如何在更新查询上创建条件

时间:2017-12-05 04:22:05

标签: php mysql

我做了一个查询,里面有条件更新。

UPDATE tbl_delivery SET amount_paid = 700000, amount_remaining = CASE WHEN 50000 < 700000 THEN 0 ELSE 50000 - 700000 END, transaction_status = IF(amount_remaining = 0, transaction_status = 'accepted', transaction_status='pending'), payment_status = CASE WHEN amount_remaining = 0 THEN payment_status = 'paid' ELSE payment_status = 'unpaid' END, modified = '2017-12-05 12:14:02' WHERE id = '1' AND user_id = '201720000003'

UPDATE tbl_delivery SET amount_paid = 700000, amount_remaining = CASE WHEN 50000 < 700000 THEN 0 ELSE 50000 - 700000 END, transaction_status = CASE WHEN amount_remaining = 0 THEN transaction_status = 'accepted' ELSE transaction_status = 'pending' END, payment_status = CASE WHEN amount_remaining = 0 THEN payment_status = 'paid' ELSE payment_status = 'unpaid' END, modified = '2017-12-05 12:01:17' WHERE id = '1' AND user_id = '201720000003'

这是我测试的查询以获得正确的结果,但发生的是它没有得到我想要的结果..

我的问题在于这个领域

    transaction_status = CASE WHEN amount_remaining = 0 THEN transaction_status = 'accepted' ELSE transaction_status = 'pending' END,
 transaction_status = IF(amount_remaining = 0, transaction_status = 'accepted', transaction_status='pending'),

而不是获得结果acceptedpending我得到的是0。

1 个答案:

答案 0 :(得分:1)

你只需要这个:

transaction_status = CASE WHEN amount_remaining = 0 THEN 'accepted' ELSE 'pending' END

也就是说,您不必重复“transaction_status =”

UPDATE tbl_delivery 
SET
        amount_paid = 700000
      , amount_remaining = CASE WHEN 50000 < 700000 THEN 0 ELSE 50000 - 700000 END
      , transaction_status = IF(amount_remaining = 0, 'accepted','pending')
      , payment_status = CASE WHEN amount_remaining = 0 THEN 'paid' ELSE 'unpaid' END
      , modified = '2017-12-05 12:14:02' 
WHERE id = '1' 
AND user_id = '201720000003'

我个人更喜欢使用case expressions,我不想鼓励在同一个查询中使用IF()和CASE,我认为这只是令人困惑。