需要有关编写优化SQL查询的建议

时间:2014-03-12 17:28:40

标签: sql postgresql-9.1 informix

我正在尝试在informix / Postgres中构建一个SQL。

以下是表格,

 Job                                JobType 
---------                          --------------------   
id,type_id,user_description          id,code,description

参考示例数据

      Job                 JobType
------------          ---------------
     1,3,'ABC'            3,'CRT','CREATE' 
     2,4,'POST1-ABC'      4,'PST1','POST1'
     3,3,'DEF'            5,'PST2','POST2' 
     4,5,'POST2-DEF' 
     5,3,'GHI'  
     6,4,'POST1-GHI'

要求是我需要获取作业尚未发布的作业表中的所有记录,可以通过查看说明找到。

注意:已发布在此处如果Job表中的user_description由POST1 +' - '或POST2 +' - '追加,则表示作业已过帐。详细说明,我创建了ABC,当我发布它时,ABC的帖子记录的描述将是'POST1-ABC'。

作业表中的user_description!=(不等于)JobType PST1 +' - '+用户说明

我已经编写了以下查询来实现上述目标

SELECT p.* FROM  Job p 
         JOIN JobType t1 ON (p.type_id = t1.id AND t1.code = 'CRT' AND LENGTH(p.user_description) > 0 )  
         WHERE p.id NOT IN (   
         select PARENT.id  from (SELECT p.id,(select description FROM JobType  WHERE code = 'PST1')||'-'||p.user_description PST1 
         ,(select description FROM JobType  WHERE code = 'PST2')||'-'||p.user_description PST2 
     FROM Job p JOIN JobType t1 ON   (p.type_id = t1.id AND t1.code = 'CRT'  AND LENGTH(p.user_description) > 0 )
     ) PARENT ,
    (   SELECT c.id,c.user_description FROM Job c JOIN JobType t   
        ON (c.type_id = t.id AND (t.code = 'PST1' OR t.code = 'PST2') AND LENGTH(c.user_description) > 0) ORDER BY 2
    )
    CHILD 
        where  (PARENT.PST2 = CHILD.user_description or PARENT.PST1 = CHILD.user_description ) 
    )

但是,如果您可以指导以更好的方式优化此查询,我将非常感谢。

编辑:

Assuming these are existing records in the table.
            Job               
    ------------        
         1,3,'ABC'            
         2,4,'POST1-ABC'     
         3,3,'DEF'            
         4,5,'POST2-DEF' 
         5,3,'GHI'  
         6,4,'POST1-GHI'
         7,3, 'XYZ'
         8,3, 'ASD

'

 Expected OUTPUT : Records which are not posted
         ---------------------
           7,3,'XYZ' 
           8,3,'ASD' 

感谢。

1 个答案:

答案 0 :(得分:1)

SELECT j.* 
FROM Job AS j
  JOIN JobType AS jt
    ON jt.id = j.type_id
WHERE jt.code = 'CRT'
  AND NOT EXISTS
      ( SELECT 1
        FROM Job AS p
          JOIN JobType AS pjt
            ON pjt.id = p.type_id 
        WHERE p.user_description = pjt.description || '-' || j.user_description
          AND pjt.code LIKE 'PST%'
      ) ;

SQL-Fiddle

进行测试