这三个更新语句可以合并吗?

时间:2013-07-17 20:18:00

标签: sql

我希望能够将这三个更新语句组合在一起,因此我不必单独运行它们。我通常会输入多个“产品”和多个“篮子”。

这个想法是能够基于“fieldB”更新两个字段< '5'或'10'或“fieldB”之间的'5'或“fieldB”> “10”没有运行三个单独的查询。

非常感谢任何帮助。

UPDATE table
set fieldA = round(8.7 * fieldA,0),
    fieldB = round(8.7 * fieldB,0)                                                                               
where product in ('APPLE','BANANA')
and basket IN ('BROWN BASKET','RED BASKET','YELLOW BASKET','BLUE BASKET')
and fieldB < '5';

UPDATE table
set fieldA = round(4.3 * fieldA,0),
    fieldB = round(4.3 * fieldB,0)                                                                               
where product in ('APPLE','BANANA')
and basket IN ('BROWN BASKET','RED BASKET','YELLOW BASKET','BLUE BASKET')
and fieldB between '5' and '10';

UPDATE table
set fieldA = round(2.5 * fieldA,0),
    fieldB = round(2.5 * fieldB,0)                                                                               
where product in ('APPLE','BANANA')
and basket IN ('BROWN BASKET','RED BASKET','YELLOW BASKET','BLUE BASKET')
and fieldB > '10';

2 个答案:

答案 0 :(得分:3)

您可以使用CASE语句,语法可能依赖于RDBMS:

UPDATE table
SET fieldA = CASE WHEN fieldB < '5' THEN round(8.7 * fieldA,0)
                  WHEN fieldB BETWEEN '5' AND '10' THEN round(4.3 * fieldA,0)
                  WHEN fieldB > '10' THEN round(2.5 * fieldA,0)
             END
    ,fieldB = CASE WHEN fieldB < '5' THEN round(8.7 * fieldB,0) 
                  WHEN fieldB BETWEEN '5' AND '10' THEN round(4.3 * fieldB,0) 
                  WHEN fieldB > '10' THEN round(2.5 * fieldB,0)  
             END                                                                            
where product in ('APPLE','BANANA')
and basket IN ('BROWN BASKET','RED BASKET','YELLOW BASKET','BLUE BASKET')

答案 1 :(得分:2)

我认为你想要的意图是:

UPDATE table
    set fieldA = round((case when fieldB < '5' then 8.7 * fieldA
                             when fieldB between '5' and '10' then 4.3 * FieldA
                             when fieldB > '10' then 2.5 * fieldA
                        end), 0),
        fieldB = round((case when fieldB < '5' then 8.7 * fieldB
                             when fieldB between '5' and '10' then 4.3 * FieldB
                             when fieldB > '10' then 2.5 * fieldB
                        end), 0)                                                                               
    where product in ('APPLE', 'BANANA') and
          basket IN ('BROWN BASKET', 'RED BASKET', 'YELLOW BASKET', 'BLUE BASKET');

但是,这正是您的原始更新所做的事情。问题是您要在每次更新中重置fieldB的值。因此,如果FieldB最初为1,则会将其设置为8.7 * FieldB = 8.7。然后,这将被第二次更新捕获,依此类推。

如果意图是级联,那么算术会略有不同。但是,条件更新背后的想法是一样的。