MySQL CASE在一个查询中设置一个额外的字段值

时间:2012-02-02 21:47:57

标签: mysql case

我正在尝试在消息表上使用CASE语句。我需要在第一个CASE语句为真时标记一条消息。

UPDATE messages
SET to_del=CASE WHEN to=2 THEN 1 ELSE to_del END,
    from_del=CASE WHEN from=2 THEN 1 ELSE from_del END,
WHERE company_id = '1'

这是在员工2删除消息之前:

company_id | to | from | to_del | from_del | viewed
    1        4     2       0         0         0
    1        2     4       0         0         0

这是在员工2删除消息之后:

company_id | to | from | to_del | from_del | viewed
    1        4     2       0         1         0    
    1        2     4       1         0         0    <-- viewed should be 1

尝试这个不起作用,但它应该在同一个查询中类似:

UPDATE messages
SET to_del=CASE WHEN to=2 THEN 1 ELSE to_del, viewed=1 END, <-- viewed=1 not working
    from_del=CASE WHEN from=2 THEN 1 ELSE from_del END,
WHERE company_id = '1'

如果第一个CASE语句为真,我怎样才能使被查看= 1?

2 个答案:

答案 0 :(得分:2)

如果逻辑真的那么简单,有没有理由不去寻求直接的解决方案;

UPDATE messages
SET to_del =   if( to=2, 1, to_del ), 
    viewed =   if( to=2, viewed, 1 ),
    from_del = if( from=2, 1, from_del )
WHERE company_id = '1'

或者,如果你真的想要消除公共子表达式(对于= 2有点矫枉过正)

UPDATE messages
SET to_del =   if( @tmp:=to=2, 1, to_del ), 
    viewed =   if( @tmp, viewed, 1 ),
    from_del = if( from=2, 1, from_del )
WHERE company_id = '1'

答案 1 :(得分:0)

试试这个。

UPDATE messages
SET to_del=CASE WHEN to=2 THEN 1 ELSE to_del END, 
    viewed = CASE WHEN to = 2 THEN 0 ELSE 1 END,
    from_del=CASE WHEN from=2 THEN 1 ELSE from_del END,
WHERE company_id = '1'