更容易做mysql UPDATE的方法?

时间:2012-01-21 15:30:29

标签: mysql if-statement

这种更新有更简单的方法吗?

UPDATE mailbox SET toNew = 1, toDelete = 0 WHERE msgID = 1 AND msgFrom = 1

UPDATE mailbox SET fromNew = 1, fromDelete = 0 WHERE msgID = 1 AND msgTo = 1

我尝试使用IF,但它不起作用......

UPDATE mailbox SET IF(msgTo = 1, toNew, fromNew) = 1, toDelete = 0 WHERE msgID = 1

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

这可以解决问题,但我更喜欢你的原始查询,因为它们更具可读性IMO

UPDATE mailbox SET toNew = IF(msgTo=1,1,toNew), toDelete = IF(msgTo=1,0,toDelete), fromNew = IF(msgFrom=1,1,fromNew), fromDelete = IF(msgFrom=1,0,fromDelete) WHERE msgID=1

答案 1 :(得分:0)

我不是100%确定你想要什么逻辑(基于你有什么标志和排列),但你可以尝试这样的事情

UPDATE mailbox 
SET 
    toNew = msgFrom, 
    fromNew = msgTo,
    toDelete = CASE WHEN msgFrom = 1 THEN 0 ELSE toDelete END,
    fromDelete = CASE WHEN msgTo = 1 THEN 0 ELSE fromDelete END
WHERE 
   msgID = 1;