需要优化查询以避免在if else条件下在查询中评估两次子查询

时间:2016-12-28 14:46:36

标签: mysql sql

我有一个查询,它使用子查询两次来获取结果在If else条件下,因为我无法保持在条件中首先评估的结果。如何优化查询?

SELECT 
    IF(
        (SELECT 
                CONVERT( IFNULL(SUM(T.hours), 0) , DECIMAL (10 , 2 )) As Val
           FROM
                time_entries T
                    JOIN
                Issues IU2 ON (t.issue_id = IU2.Id)
           Where
                IU2.id = IU.Id)  <> 0,

         (SELECT 
                CONVERT( IFNULL(SUM(T.hours), 0) , DECIMAL (10 , 2 )) As Val
            FROM
                time_entries T
                    JOIN
                Issues IU2 ON (t.issue_id = IU2.Id)
            Where
                IU2.id = IU.Id),
         99    
       ) AS NotCovered
FROM
    issues IU
        Join
    custom_values CV ON (IU.project_id = CV.customized_id
        AND CV.value = '')
where
    IU.done_ratio <> 100;

1 个答案:

答案 0 :(得分:0)

首先尝试计算所有内容并将其存储在临时表中,然后可以在临时表上执行IIF或CASE。