postgresql - 如何在 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 Linoff,Laurenz Albe,ex4建议的答案(感谢您的支持),
我更新如下:
查询数据库中是否已经存在数据:
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语句可以吗?
或者在这种情况下我怎样才能做得好,请告诉我!
任何提示都会很棒。谢谢!
解决方案
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.
推荐阅读
- ocaml - ocaml 尾递归函数
- html - 文本不会环绕图像弹性框
- javascript - 更改动态创建的 iframe 的 src
- javascript - 检查对象是否等于某种类型的良好实践方法是什么?
- regex - REGEX - 如何递归地捕获一个组?
- php - 可变长度数据
- javascript - Vue.js 错误:命名槽必须使用 '' on a custom element
I am trying to pass information through slots and I keep getting an error,
'Named slots must use '' on a custom element.'
See below for my code.<
- python - 接收字母字符时如何防止python程序崩溃
- jquery - 如何从包含另一个元素的 jQuery Datatable 列中过滤
- matlab - ADAM(阿姆斯特丹)工具箱试验掩蔽稳健去趋势在 Matlab 中引发错误