根据旧值更新多个字段

时间:2014-01-06 13:09:36

标签: mysql

我已经测试了这个查询(见下文)并且它无效

我有这张表:

id     A      B      C
-----------------------
1      1      2     
2             3     
3      2             4
4      6      2      1
-----------------------

我想在第一个空字段中将A,B或C设置为4,除非4已经在A,B或C中。

因此,如果(条件1) A!= 4且B!= 4且C!= 4 => (条件2)如果A!=“”转到B,如果B!=“”转到C,如果C!=“”跳过更新。

In my example 
row 1: C => 4
row 2: A => 4
row 3: not updated (4 allready exists)
row 4: not updated (no empty field)

我提出的查询:

UPDATE table SET 
    A=IF(A!="",A,4),                 //1:
    B=IF(A="" OR B!="",B,4),         //2:
    C=IF(A="" OR B="",C,4)           //3:
WHERE (A!="" OR B!="" OR C!="")      //4:
       AND (A!=4 AND B!=4 AND C!=4)  //5: 

       // 1: if A="", make it 4, else keep value  
       // 2: if A was "" it should be 4 by now, let B be B, else make B 4
       // 3: if A was "" or B was "", one of them should be 4 by now, else make C 4
       // 4: eliminates row 4 (check if there's a free field)
       // 5: eliminates row 3 (condition 1)

这个查询是否有效(特别是第2部分和第3部分)取决于mySQL的作用:它会查看IF语句中字段的 OLD 值,还是首先更新一个字段和然后将新值带到下一部分?测试朗姆酒失败了,它将所有空字段更新为4,表明它考虑了新值。

所以我的问题是:我该怎么做才能使查询符合我的条件?

[编辑]

不是最优雅的查询,但这有效:

UPDATE table SET 
    A=IF( A<>"",A,4),                
    B=IF( (A="" OR A=4) OR B<>"",B,4),        
    C=IF( (A="" OR A=4) OR (B="" OR B=4) OR C<>"",C,4)         
WHERE (A!="" OR B!="" OR C!="")     
       AND (A!=4 AND B!=4 AND C!=4) 

似乎mySQL将A的新值带到B的IF语句中,并将A和B的新值带到C

1 个答案:

答案 0 :(得分:1)

UPDATE table SET 
    A=IF(A is null,4,A),   -- if a is null, set it to 4            
    B=IF(A is not null and b is null,4,B),       -- if A did not meet the condition to set to 4 but B is null, set B to 4
    C=IF(A is not null and B is not null and C is null ,4,C) --  if A or B did not meet the condition to be set to 4 and C is null, set c to 4
WHERE (a+b+c is null)     --- short of "a is null or b is null or c is null"
       AND (A!=4 AND B!=4 AND C!=4)