sql中有多个相互关联的循环

时间:2013-07-21 23:10:46

标签: mysql sql loops subquery correlated-subquery

Loop1是通过一些简单的逻辑推导出来的。 Loop2是通过一个非常复杂的逻辑派生出来的。 Loop3非常简单,只需通过向Loop2

添加2即可得到

现在,我想通过Loop1,Loop2和amp;组合来推导Loop4。循环3。问题是loop2是一个非常繁重的逻辑,如果我在Loop3中再次导出逻辑,查询运行速度非常慢。为了提供更清晰,我使用loop1& 2和loop4使用loop1,2& 3找到loop3。请建议一种方法来使此查询工作。

select sre.shipmentId, 
       loop1.TRY1, 
       loop2.TRY2, 
       loop3.TRY3, 
       (select case when u>0 then loop1.TRY1 when u>1 then loop2.TRY2 else loop3.TRY3 end) as loop4
from `shipmentRouteEvent` sre
left join (select sre1.shipmentId as s1, (case when .....>0 then .... end) ad TRY1
           from `shipmentRouteEvent` sre1
           where sre1.updateDate='2013-07-01'
          ) as loop1 on sre.id=try1.id
left join (select some heavy logic which will modify TRY1 to TRY2) as loop2
left join (select (TRY2+2) as TRY3) as loop3
where sre.updateDate='2013-07-01'

1 个答案:

答案 0 :(得分:0)

我认为您希望将其作为嵌套子查询执行此操作:

from (select . . .
      fro (select . . .
           from `shipmentRouteEvent` sre left join
                 (select sre1.shipmentId as s1, (case when .....>0 then .... end) ad TRY1
                  from `shipmentRouteEvent` sre1
                  where sre1.updateDate='2013-07-01'
                ) loop1
                on sre.id=try1.id
           ) loop1 left join
           (select some heavy logic which will modify TRY1 to TRY2
           ) loop2
           on . . .
      ) loop2 left outer join
      (. . .
      ) loop3
      on . . .

每个嵌套级别都允许您在下一级使用结果,因此不需要重新计算结果。