2017-08-30 41 views
0

假設我有這張索引表。PostgreSQL索引運行時間

Create Table sample 
(
    table_date timestamp without timezone, 
    description 
); 
    CREATE INDEX dailyinv_index 
    ON sample 
    USING btree 
    (date(table_date)); 

而且它有3300萬行。

爲什麼是它運行此查詢

select count(*) from sample where date(table_date) = '8/30/2017' and desc = 'desc1' 

產生的結果@ 12ms的

使用PostgreSQL解釋查詢計劃。這就是它所做的。

Aggregate (cost=288678.55..288678.56 rows=1 width=0) 
     ->Bitmap Heap Scan on sample (cost=3119.63..288647.57 rows=12393 width=0) 
      Recheck Cond: (date(table_date) = '2017-08-30'::date) 
      Filter: ((description)::text = 'desc1'::text) 
       -> Bitmap Index Scan on dailyinv_index (cost=0.00..3116.54 rows=168529 width=0) 
        Index Cond: (date(table_date) = '2017-08-30'::date) 

但經過11460毫秒這一個

select date(table_date) from sample where date(table_date)<='8/30/2017' order by table_date desc limit 1 

產量造成?

查詢計劃

Limit (cost=798243.52..798243.52 rows=1 width=8) 
    -> Sort (cost=798243.52..826331.69 rows=11235271 width=8) 
      Sort Key: table_date 
        -> Bitmap Heap Scan on sample (cost=210305.92..742067.16 rows=11235271 width=8) 
         Recheck Cond: (date(table_date) <= '2017-08-30'::date) 
          -> Bitmap Index Scan on dailyinv_index (cost=0.00..207497.10 rows=11235271 width=0) 
            Index Cond: (date(table_date) <= '2017-08-30'::date) 

PostgreSQL的版本:9.4

也許我做索引錯誤或我不知道。真的不熟悉索引。任何幫助都會很棒。非常感謝!

+1

請參閱:https://stackoverflow.com/tags/postgresql-performance/info。另外,您的索引位於不同的表格中。 –

+0

對不起。我剛剛複製了我的實際表格並進行了編輯。 – Bigboss

+0

仍然是錯誤的列。並請包括解釋分析結果。 –

回答

1

您的問題是由您在table_date而不是date(table_date)上排序造成的。這可以通過將查詢修改爲:

SELECT DATE(table_date) 
FROM sample 
WHERE DATE(table_date) <= '8/30/2017' 
ORDER BY DATE(table_date) DESC 
LIMIT 1 
+0

是的。它有所不同。謝謝 – Bigboss