我有一個表call_logs,它包含一個ID,DEVICE_ID,時間戳和其他一些領域一起變量。 我目前正試圖編寫一個查詢,返回最後一次調用,如果它正在爲每個設備工作。 當前我的查詢是這樣的:,Postgres的查詢與指數僅緩慢掃描
SELECT DISTINCT ON (device_id) c.device_id, c.timestamp, c.working, c.id
FROM call_logs c
ORDER BY c.device_id, c.timestamp desc;
它返回我想要的信息。 但是我的生產服務器現在變得相當龐大,我在表中有大約6,000,000條記錄。
我增加了一個索引的表:
CREATE INDEX cl_device_timestamp
ON public.call_logs USING btree
(device_id, timestamp DESC, id, working)
TABLESPACE pg_default;
但我得到什麼,我認爲是很慢的時間: 這裏是一個解釋分析F中的查詢:
EXPLAIN ANALYSE SELECT DISTINCT ON (device_id) c.device_id, c.timestamp, c.working, c.id
FROM call_logs c
ORDER BY c.device_id, c.timestamp desc;
QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
Unique (cost=0.56..363803.37 rows=120 width=25) (actual time=0.069..2171.201 rows=124 loops=1)
-> Index Only Scan using cl_device_timestamp on call_logs c (cost=0.56..347982.87 rows=6328197 width=25) (actual time=0.067..1594.953 rows=6331024 loops=1)
Heap Fetches: 8051
Planning time: 0.184 ms
Execution time: 2171.281 ms
(5 rows)
我只有124個唯一的device_id。我不會認爲這將是一個緩慢的過程與索引?任何想法出了什麼問題?或者爲什麼它如此緩慢?
怎麼樣的執行時間,如果你刪除'DISTINCT'?如果你只想要最後一次調用,你不能添加'LIMIT 1'並且不需要'DISTINCT'嗎? –
儘量避免截然不同,請參閱:https://dba.stackexchange.com/questions/93158/how-to-speed-up-select-distinct – Tisp
但限制1只給我1個設備1每個設備需要1個 – user1434177