我对正确的索引有疑问。我用的是rails 3.2.13,后面用的是Posgresql。顺便说一句,可能更多的是关系数据库/索引问题......
我有这张桌子:
# Table name: exams
#
# id :integer not null, primary key
# cognomenome :string(255)
# matricola :string(255)
# corsolaurea :string(255)
# annoaccademico :string(255)
# blablabla
#
# Indexes
#
# index_exams_on_annoaccademico (annoaccademico)
# index_exams_on_cognomenome (cognomenome)
# index_exams_on_corsolaurea (corsolaurea)
# index_exams_on_matricola (matricola)
我想查询数千条记录表(记录的数量每年线性增加,比如每年增加500条,即十年增加5000-6000条);
我必须进行这些查询:
SELECT "exams".* FROM "exams" WHERE (upper(cognomenome) like '%GIORGIO%') ORDER BY annoaccademico desc, corsolaurea, cognomenome LIMIT 50 OFFSET 0
或者那个:
SELECT "exams".* FROM "exams" WHERE (matricola like '%8327483274%') ORDER BY annoaccademico desc, corsolaurea, cognomenome LIMIT 50 OFFSET 0
或者那个:
SELECT "exams".* FROM "exams" WHERE (annoaccademico = '2013') AND (upper(cognomenome) like '%GIORGIO%') ORDER BY annoaccademico desc, corsolaurea, cognomenome LIMIT 50 OFFSET 0
或者那个:
SELECT "exams".* FROM "exams" WHERE (corsolaurea = 'Infermieristica') AND (upper(cognomenome) like
'%GIORGIO%') ORDER BY annoaccademico desc, corsolaurea, cognomenome LIMIT 50 OFFSET 0
或者那个:
SELECT "exams".* FROM "exams" WHERE (corsolaurea = 'Medicina-Anatomia I' and annoaccademico = '2013') AND (upper(cognomenome) like '%GIORGIO%') ORDER BY annoaccademico desc, corsolaurea, cognomenome LIMIT 50 OFFSET 0
简而言之,我使用列 annoaccademico corsolaurea cognomenome matricola 的一些 AND 组合来查询表
我总是必须按列排序:annoaccademico desc corsolaurea cognomenome
我的问题:
1)考虑到表的大小,你是否建议使用索引?2)如图所示,我已经在单列上设置了索引;对吗?3)可能我需要添加两个多列索引,例如:
add_index :exams, [:annoaccademico, :corsolaurea, :cognomenome]
add_index :exams, [:annoaccademico, :corsolaurea, :matricola]
这是正确的 ?
对我来说不是很清楚的一点是:除了选择条件,索引对 order by 子句也有用吗?
非常感谢您的耐心/我的 db/sql 无知。giorgio solyaris.altervista.org