改进row_number()下面的查询(分区依据)

时间:2016-11-11 05:53:35

标签: sql oracle window-functions

有没有办法改进下面的查询,当我只检查一条记录时它的工作速度更快(NAME =' T 104')但是当所有现有的(113条记录)记录没有NAME =&#时39; T 104'它需要大约5秒钟:

以下一项需要73毫秒:

$( document ).ready(function() {
    $.ajax({
    type: "POST",
    url: '<?php echo base_url(); ?>list/people',
    success: function(response) {   
        $('#example').dataTable({
            "bProcessing": true,
            "bDestroy": true,
            "data": response, // <-- your array of objects
            "columns": [
                {"data": "id"}, 
                {"data": "username"},
                {"data": "contactno"}
             ]
        });
    }, 
    });
});

以下一个需要4秒:

select 
    name, PRODUCTION_DAY, daytime 
from
    (select 
         name, PRODUCTION_DAY, daytime, 
         row_number() over (partition by name order by daytime desc) as seqnum
     from 
         RESULT_1 t 
     where 
         PRODUCTION_DAY < '15-May-2015'
    ) 
where 
    seqnum = 1 and NAME = 'T  104' 

谢谢, 小号

2 个答案:

答案 0 :(得分:-1)

在“name”列上添加索引

2个查询之间的区别是where子句中的额外谓词。

您还可以尝试按名称将过滤器放在派生表

select 
    name, PRODUCTION_DAY, daytime 
from
    (select 
         name, PRODUCTION_DAY, daytime, 
         row_number() over (partition by name order by daytime desc) as seqnum
     from 
         RESULT_1 t 
     where 
         PRODUCTION_DAY < '15-May-2015'
      and NAME = 'T  104' 
    ) 
where 
    seqnum = 1 

答案 1 :(得分:-1)

我认为当您重写这样的查询时,您应该得到相同的结果:

SELECT NAME, 
    MAX(PRODUCTION_DAY) KEEP (DENSE_RANK FIRST ORDER BY daytime) AS PRODUCTION_DAY, 
    MIN(daytime) AS daytime
FROM RESULT_1  
WHERE PRODUCTION_DAY < '15-May-2015'
    AND NAME = 'T  104'
GROUP BY NAME;

根据您的索引,这可能是最快的方法。