首页 > 解决方案 > 如何在 Postgres 中使用创建索引来优化搜索

问题描述

我有一个包含 300,000,000 条记录的数据库,
要插入新记录,我想检查记录是否已经在数据库中,
我使用以下查询来确认:

SELECT student_code
FROM public.student_tbl
WHERE class_type='high_school' AND class_register='true' AND (student_code='F40101197X0' OR student_code='F40101197X1' OR student_code='F40101197X2');

完成需要2分钟,需要相当长的时间。
因此,我想通过使用以下查询来节省检查数据是否已在数据库中的时间:

CREATE INDEX student_tbl_class_register_index
ON public.student_tbl(class_register)
WHERE class_register IS TRUE; 

UPDATE1:
・[student_id] to [student_code]
・<code>class_type,student_code是可以更改的值,同时class_register决定是否插入新记录,如果class_register='false'可以插入新记录。

UPDATE2:
作为Gordon LinoffLaurenz Albeex4建议的答案(感谢您的支持),
我更新如下:

查询数据库中是否已经存在数据:

SELECT student_code
FROM public.student_tbl
WHERE class_type = 'high_school' AND
      class_register = 'true' AND
      student_code IN ('F40101197X0', 'F40101197X1', 'F40101197X2');

查询创建索引:

CREATE UNIQUE INDEX CONCURRENTLY studenttbl_classtype_studentcode_idx
ON public.student_tbl (class_type, student_code)
WHERE class_register = 'true';

ALTER TABLE public.student_tbl
ADD CONSTRAINT studenttbl_classtype_studentcode_idx
UNIQUE USING INDEX studenttbl_classtype_studentcode_idx;

上面的CREATE INDEX语句可以吗?
或者在这种情况下我怎样才能做得好,请告诉我!
任何提示都会很棒。谢谢!

标签: postgresqlindexing

解决方案


For this query:

SELECT student_id
FROM public.student_tbl
WHERE class_type = 'high_school' AND
      class_register = 'true' AND
      student_id IN ('F40101197X0', 'F40101197X1', 'F40101197X2');

You want an index on student_tbl(class_type, class_register, student_id).

However, if you want to guarantee that rows are not duplicated, then you should be using a unique index or constraint.


推荐阅读