我们说我有一个包含多列的表格:
CREATE TABLE offers (
id integer NOT NULL, -- not queried, just a unique id
rooms integer,
price integer,
size integer,
hood_id integer,
city_id integer,
... (some other columns, not queried)
);
用户使用上述列的多种组合对该表进行查询。有时他们只通过一列查询,有时候只查询所有列。我希望涵盖所有案例以获得最佳表现。
所以问题是单独索引每一列是否足够:
CREATE INDEX index_offers_on_rooms ON offers USING btree (rooms);
CREATE INDEX index_offers_on_price ON offers USING btree (price);
CREATE INDEX index_offers_on_size ON offers USING btree (size);
CREATE INDEX index_offers_on_hood_id ON offers USING btree (hood_id);
CREATE INDEX index_offers_on_city_id ON offers USING btree (city_id);
并为上述所有内容创建一个索引:
CREATE INDEX index_all_offers_data ON offers USING btree (rooms, price, size, hood_id, city_id);
或者我应该涵盖所有可能的情况,例如:
CREATE INDEX index_offers_on_rooms_and_price ON offers USING btree (rooms, price);
CREATE INDEX index_offers_on_rooms_and_size ON offers USING btree (rooms, size);
CREATE INDEX index_offers_on_rooms_and_price_and_size ON offers USING btree (rooms, price, size);
...
以上看起来并不正确,因为更新和插入会变得非常慢。这些记录不会被更新,但是会有很多创建(每小时至少600条记录)和删除。