等于运算符使用索引,但不使用运算符

时间:2019-05-28 14:40:19

标签: postgresql

我有一张表,其中有一个时间戳类型列和一个具有组合索引的数字列

table leads
(
DISPLAY_ID numeric(10),
REC_DATE timestamp without time zone,
SUP_ID numeric(10),
DISTANCE  numeric(10),
RELAX_FLAG numeric(10)
)
"sampletable_indx1" btree ( date(REC_DATE), SUP_ID )

当我在两列上都使用等号(=)运算符运行查询时,它运行良好

样本查询1

    SELECT
COUNT(SUP_ID) COUNT,
SUM(CASE WHEN DISTANCE BETWEEN 0 AND 50 THEN 1 ELSE 0 END) CNT_50
FROM
(
SELECT
DISPLAY_ID,SUP_ID, DISTANCE
FROM
LEADS
WHERE
date(REC_DATE)=date(now())
AND SUP_ID = 30628898
AND RELAX_FLAG IN (6,7)
)a;

                                                               QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=2.80..2.81 rows=1 width=16) (actual time=0.022..0.022 rows=1 loops=1)
   ->  Index Scan using sampletable_indx1 on LEADS (cost=0.57..2.79 rows=1 width=10) (actual time=0.021..0.022 rows=0 loops=1)
         Index Cond: ((date(REC_DATE) = date(now())) AND (SUP_ID= '30628898'::numeric))
         Filter: (RELAX_FLAG = ANY ('{6,7}'::numeric[]))
 Planning time: 0.213 ms
 Execution time: 0.070 ms

但是当我为其中一列的In运算符运行它时,它没有正确使用索引

示例查询2

    SELECT
COUNT(SUP_ID) COUNT,
SUM(CASE WHEN DISTANCE BETWEEN 0 AND 50 THEN 1 ELSE 0 END) CNT_50
FROM
(
SELECT
DISPLAY_ID,SUP_ID, DISTANCE
FROM
LEADS
WHERE
date(REC_DATE)=date(now())
AND SUP_ID IN (30628898, 23767294,  2888493, 58887272, 16226505,  1726042, 39068344, 10544691,  1445776, 24007105)
AND RELAX_FLAG IN (6,7)
)a; 

                                                                QUERY PLAN

-------------------------------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=2.81..2.82 rows=1 width=16) (actual time=1065.310..1065.311 rows=1 loops=1)
   ->  Index Scan using sampletable_indx1 on LEADS (cost=0.57..2.80 rows=1 width=10) (actual time=88.814..1065.259 rows=11 loops=1)
         Index Cond: (date(REC_DATE) = date(now()))
         Filter: ((RELAX_FLAG = ANY ('{6,7}'::numeric[])) AND ( SUP_ID = ANY ('{30628898, 23767294,  2888493, 58887272, 16226505,  1726042, 39068344, 10544691,  1445776, 24007105}'::numeric[])))
         Rows Removed by Filter: 680096
 Planning time: 0.299 ms
 Execution time: 1065.357 ms

可能是相同的原因,如何解决?

0 个答案:

没有答案