我该如何缩短这个SQL?

时间:2012-02-16 13:15:56

标签: sql

我需要运行这四次,我怎么能在一行中完成,或者可能是更少的行

update opp set run_mode = 0, run_time = 0, 
where oppar_job_name in ('ABC') ) and oppar_job_rec in ('ABC');

update opp set run_mode = 0, run_time = 0, 
where oppar_job_name in ('DEF') ) and oppar_job_rec in ('DEF');

update opp set run_mode = 0, run_time = 0, 
where oppar_job_name in ('FGH') ) and oppar_job_rec in ('FGH');

update opp set run_mode = 0, run_time = 0, 
where oppar_job_name in ('IJK') ) and oppar_job_rec in ('IJK');

我正在考虑尝试这个。

update opp set run_mode = 0, run_time = 0, 
where oppar_job_name in (
'ABC',
'DEF',
'FGH',
'IJK'
) and oppar_job_rec in 
(
'ABC',
'DEF',
'FGH',
'IJK'
);

上面的事情是否正确。 我的意思是表中有一对一的对应关系,如

ABC ABC
DEF DEF
FGH FGH
IJK IJK

3 个答案:

答案 0 :(得分:6)

如果我理解得很好:

update opp set run_mode = 0, run_time = 0, 
where (oppar_job_name = oppar_job_rec) and 
      (oppar_job_rec in ('ABC','DEF','FGH','IJK'));

附加括号更好; - )

答案 1 :(得分:1)

如果列之间存在一对一的对应关系,那么您的解决方案是正确的(但语法错误)并且unludo的解决方案更好。

否则,您可以通过避免多个更新语句来使其更简洁:

update opp set 
    run_mode = 0, run_time = 0
where 
    (oppar_job_name in ('ABC') and oppar_job_rec in ('ABC')) OR
    (oppar_job_name in ('DEF') and oppar_job_rec in ('DEF')) OR
    (oppar_job_name in ('FGH') and oppar_job_rec in ('FGH')) OR
    (oppar_job_name in ('IJK') and oppar_job_rec in ('IJK'));

最后你甚至不需要使用in运算符,所以你可以这样写:

update opp set 
    run_mode = 0, run_time = 0
where 
    (oppar_job_name = 'ABC' and oppar_job_rec = 'ABC') OR
    (oppar_job_name = 'DEF' and oppar_job_rec = 'DEF') OR
    (oppar_job_name = 'FGH' and oppar_job_rec = 'FGH') OR
    (oppar_job_name = 'IJK' and oppar_job_rec = 'IJK');

答案 2 :(得分:1)

如果你的oppar_job_name和oppar_job_rec谓词总是相同的,我更喜欢unludo的答案。

否则,如果参数可能不同,您可以执行以下操作:

update opp set run_mode = 0, run_time = 0
where ( oppar_job_name, oppar_job_rec )
in ( ('ABCname' , 'ABCrec')
   , ('DEFname' , 'DEFrec')
   , ('FGHname' , 'FGHrec')
   , ('IJKname' , 'IJKrec')
   );