[英]Improve query that uses Seq Scan using indexes
我正在嘗試優化此查詢。 它正在執行順序掃描,它與行數呈線性增長。
SELECT "class"."starts_at"
FROM "class"
WHERE ("class"."starts_at" >= 2021-12-16 14:13:19.824533+00:00
AND "class"."starts_at" BETWEEN 2021-12-01 00:00:00+05:00 AND 2021-12-31 23:59:59+05:00
AND "class"."status" = reserved
AND "class"."teacher_id" = 3)
Query PlanSeq Scan on class (cost=0.00..1.18 rows=1 width=8) (actual time=0.029..0.056 rows=1 loops=1)
Filter: ((starts_at >= '2021-12-16 14:13:19.824533+00'::timestamp with time zone) AND (starts_at >= '2021-11-30 19:00:00+00'::timestamp with time zone) AND (starts_at <= '2021-12-31 18:59:59+00'::timestamp with time zone) AND ((status)::text = 'reserved'::text) AND (teacher_id = 3))
Rows Removed by Filter: 7
Planning Time: 0.138 ms
Execution Time: 0.138 ms
當我為starts_at
、 status
和teacher
添加索引時,它沒有使用索引。
BEGIN;
--
-- Create index starts_at_status_teacher_idx on field(s) starts_at, status, teacher of model class
--
CREATE INDEX "starts_at_status_teacher_idx" ON "class" ("starts_at", "status", "teacher_id");
COMMIT;
我需要添加什么索引以使其更快?
您的索引應該是:
CREATE INDEX X0001 ON "class" (teacher_id, status, starts_at);
當謂詞中存在不等式和相等性時,必須首先在索引鍵中設置相等的列,最后設置不等式列...
如果您在 Microsoft SQL 服務器中執行了此查詢,優化器會按照鍵中列的正確順序為您提供正確的索引...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.