如何在Oracle SQL中将两个查询合并为一个

时间:2018-11-15 19:01:09

标签: sql oracle

我们在生产中出现错误,幸运的是有一个手动的解决方案,但是我每天早上必须在两个查询中运行以更正错误。这是如此手动,我想将其自动化并将两个查询合并为一个。但是,如果我搞混了会导致混乱的合并查询,那么在生产中只会出现此错误,而在DEV或QA中不会出现此错误,因此,我需要您的专业知识。

第一个查询带来项目编号

select id,  ugenProjectNumber
from unifier_uxpecai
where (pecaiChecklistNumber = 0 or pecaiChecklistNumber is null)
or (pecaiChecklistItemNumber = 0 or pecaiChecklistItemNumber is null)

第二查询解决了操作项和列表项之间断开的链接,我手动将第一查询结果的唯一项目编号放入第二查询,并针对每个唯一的项目编号运行第二查询。

update unifier_uxpecai pai
set (pai.pecaiChecklistNumber, pai.pecaiChecklistItemNumber) =
(
   select pcl.id, pcli.id
   from unifier_uxpecl pcl
   inner join unifier_uxpecl_lineitem pcli on pcli.uuu_tab_id = 0 and 
   pcli.record_id = pcl.id
   where pcl.ugenProjectNumber = 'GL-16-161010-143502'
   and pcli.pecItemActionItemBPC = pai.id
)
where exists
(
   select pcli.pecItemActionItemBPC
   from unifier_uxpecl pcl
   inner join unifier_uxpecl_lineitem pcli on pcli.uuu_tab_id = 0 and 
   pcli.record_id = pcl.id
   where pcl.ugenProjectNumber = 'GL-16-161010-143502'
   and pcli.pecItemActionItemBPC = pai.id
)
and (pai.pecaiChecklistNumber = 0 or pai.pecaiChecklistItemNumber = 0)

1 个答案:

答案 0 :(得分:1)

您可以将逻辑合并到查询中:

update unifier_uxpecai pai
set (pai.pecaiChecklistNumber, pai.pecaiChecklistItemNumber) =
(select pcl.id, pcli.id
 from unifier_uxpecl pcl join
      unifier_uxpecl_lineitem pcli
      on pcli.uuu_tab_id = 0 and pcli.record_id = pcl.id
 where pcl.ugenProjectNumber in (select ugenProjectNumber
                                 from unifier_uxpecai
                                 where (pecaiChecklistNumber = 0 or pecaiChecklistNumber is null) or
                                       (pecaiChecklistItemNumber = 0 or pecaiChecklistItemNumber is null
                                ) and
       pcli.pecItemActionItemBPC = pai.id
)
where exists
(
   select pcli.pecItemActionItemBPC
   from unifier_uxpecl pcl join
        unifier_uxpecl_lineitem pcli
        on pcli.uuu_tab_id = 0 and 
           pcli.record_id = pcl.id
   where pcl.ugenProjectNumber in (select ugenProjectNumber
                                   from unifier_uxpecai
                                   where (pecaiChecklistNumber = 0 or pecaiChecklistNumber is null) or
                                         (pecaiChecklistItemNumber = 0 or pecaiChecklistItemNumber is null
                                  ) and
        pcli.pecItemActionItemBPC = pai.id
) and
(pai.pecaiChecklistNumber = 0 or pai.pecaiChecklistItemNumber = 0)