在Postgres中优化大小写/解码查询

时间:2018-11-09 06:03:08

标签: postgresql subquery sqlperformance

有人可以帮助我以其他方式实施以下查询吗?我面临性能问题,因为在多个SELECT语句中到处都使用相同的多个CASE语句。

我的代码很大,很大一部分在这里:

        select col1,col2,
    ( CASE 
    WHEN NOT EXISTS (SELECT
                        CASE over.ola
                            WHEN NULL::text THEN 'NT'::character varying
                        END AS tover 
                    FROM   tsmt over 
                    WHERE  over.cod = hfprc.cod 
                            AND over.vdat = nav.vdat) THEN 'NT' 
    ELSE (SELECT CASE over.ola
                            WHEN NULL::text THEN 'TT'::character varying END
            FROM   tsmt over 
            WHERE  over.cod = hfprc.cod 
                AND over.vdat = nav.vdat) 
    END )
        olaflag, 
    (SELECT description 
    FROM   tolahfp tover 
    WHERE  tover.ola = (SELECT CASE 
                                    WHEN NOT EXISTS (SELECT
                                        CASE over.ola
    WHEN NULL::text THEN 'TT'::character varying
                                        END AS 
            tover 
                    FROM   tsmt over 
                    WHERE  over.cod = hfprc.cod 
                        AND over.vdat = nav.vdat) THEN 'TT' 
            ELSE (SELECT CASE over.ola
    WHEN NULL::text THEN 'TT'::character varying
                                        END AS tover 
            FROM   tsmt over 
            WHERE  over.cod = hfprc.cod 
                AND over.vdat = nav.vdat) 
            END ola 
        )) 
        ola,--ola description 

        (CASE thfp.codcag::text
                WHEN NULL::text THEN 'CCCC'::character varying
            END 
        )codcag, 
    (SELECT conf.descag 
    FROM   thfconagrhfp conf 
    WHERE  conf.codcag = CASE thfp.codcag::text
                        WHEN NULL::text THEN 'CCCC'::character varying
                    END) 
        desccag, 
    thfp.frq, 
    thfp.flgcal 
    FROM   thpr hfprc LEFT JOIN tgrpprchfp grp ON hfprc.cgrp = grp.cgrp 

        LEFT JOIN tnav nav ON hfprc.cod = nav.cod AND nav.flag = 'Y' 
        LEFT JOIN thf thfp ON  hfprc.cod = thfp.cod
        LEFT JOIN tsmtdatthdhfp smtdatthd ON hfprc.cod = smtdatthd.cod

1 个答案:

答案 0 :(得分:0)

您是否使用sqlsmith来编写查询?

但是,更重要的是,此处的解决方法是用外部联接替换子选择。

例如:

SELECT CASE WHEN NOT EXISTS (SELECT weirdfunc(x.x1)
                             FROM x
                             WHERE x.x2 = y.y2
                               AND x.x3 = z.z3)
            THEN 'Constant'
            ELSE (SELECT otherweirdfunc(x.x1)
                  FROM x
                  WHERE x.x2 = y.y2
                    AND x.x3 = z.z3)
       END
FROM y
   LEFT JOIN z USING (t);

会更好,更高效地写为

SELECT coalesce(otherweirdfunc(x.x1), 'Constant')
FROM y
   LEFT JOIN z USING (t)
   LEFT JOIN x ON x.x2 = y.y2 AND x.x3 = z.z3;

我的经验法则是:除了FROM子句之外,子选择通常在任何地方都是错误的。