Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Database 组合索引的Postgres顺序_Database_Performance_Postgresql_Indexing - Fatal编程技术网

Database 组合索引的Postgres顺序

Database 组合索引的Postgres顺序,database,performance,postgresql,indexing,Database,Performance,Postgresql,Indexing,我有一个包含10万行数据的表 CREATE TABLE log_info ( id serial NOT NULL, created_date date, # date in month - max 30-31 distinct value dept_id integer, # max 50 distinct value group_id integer, # 10000 distinct value ....... ) 大多数查询都基于创建日期、部门id和组id,因此我想

我有一个包含10万行数据的表

CREATE TABLE log_info
(
  id serial NOT NULL,
  created_date date, # date in month - max 30-31 distinct value
  dept_id integer, # max 50 distinct value
  group_id integer, # 10000 distinct value
  .......
)
大多数查询都基于创建日期部门id组id,因此我想为3个字段创建组合索引

我知道组合索引的顺序会影响数据库性能,所以在我的例子中,哪一个是最好的索引

CREATE INDEX log_info_index1 ON log_info USING btree (created_date, dept_id, group_id);


哪种顺序最好取决于您计划运行哪种查询。考虑下面的例子:

WHERE created_date=? AND dept_id=?
WHERE created_date=? AND dept_id>=?
WHERE created_date=? AND dept_id=? AND group_id BETWEEN ? AND ?
对于所有这些索引,可以使用索引
(创建日期、部门id、组id)
,而不能使用索引
(创建日期、组id、部门id)
。通常,如果您在
(a、b、c)
上有索引,那么它可以用于以下情况

a=?
a=? AND b=?
a=? AND b=? AND c=?
a=? AND {comparison involving b}
a=? AND b=? AND {comparison involving c}

其中比较是指
中的一个,如果a有5个不同的值,b有100个不同的值,c有5000个不同的值,查询a=?b=?和c>=?。哪一个是最好的顺序索引?(a,b,c),(a,c,b),(c,b,a),…然后
(b,a,c)
a=?
a=? AND b=?
a=? AND b=? AND c=?
a=? AND {comparison involving b}
a=? AND b=? AND {comparison involving c}
a=? AND b=? AND c>=?