简体   繁体   English

索引查询优化= SQL

[英]Indexed Query Optimisation = SQL

This is a part of my past exam questions - 这是我过去考试题的一部分 -

Optimise the following and assume there is an index on Members.lname : 优化以下内容并假设Members.lname上有一个索引:

SELECT fname, lname 
FROM Members 
WHERE lname <> 'Rogers' 
  AND memberType='Student'; 

I have therefore tried: 因此我尝试过:

SELECT fname, lname 
FROM Members 
WHERE lname > 'Rogers' OR lname < 'Rogers'AND memberType='Student'; 

I tried this as splitting the <> forces the use of the index - my answer is however wrong. 我试过这个,因为分裂<>强制使用索引 - 但我的回答是错误的。 I was wondering if anyone could help and point me in the right direction? 我想知道是否有人可以提供帮助并指出我正确的方向?

In my opinion the original query itself cannot be optimized. 在我看来,原始查询本身无法进行优化。

That there is an index on lname should have no impact on the query. lname有索引应该对查询没有影响。 All members will have a name and few members will be Rogers. 所有成员都有一个名字,很少有成员将成为罗杰斯。 So the DBMS should not use the index, but simply read the full table. 所以DBMS不应该使用索引,而只是读取整个表。

"Optimise the following", however, may allow to optimize the query indirectly by creating another index. 但是,“优化以下内容”可能允许通过创建另一个索引来间接优化查询。 This index should at least contain and start with memberType : 该索引至少应包含并以memberType

create index idx1 on members (membertype);

Whether this index will be used for the query will probably depend on what's in the table. 此索引是否将用于查询可能取决于表中的内容。 If 99% of the members are students, the DBMS should read the full table instead. 如果99%的成员是学生,则DBMS应该读取完整的表格。 If it's only few students (say 3%) then using the index makes sense, and the DBMS would use the index to find the students in the table and then check lname in the record. 如果只有少数学生(比如说3%),那么使用索引是有意义的,DBMS会使用索引查找表中的学生,然后检查记录中的lname

Having said this, we might want this instead: 说完这个,我们可能会想要这个:

create index idx2 on members (membertype, lname);

so the DBMS reads the index, finds the students, sees immediately if the name is Rogers, and only accesses the table for the desired records. 所以DBMS读取索引,找到学生,立即看到名称是否为Rogers,并且只访问表中所需的记录。

An even better index still would be a covering index containing all columns in question, so the table doesn't have to be read anymore, as all the information is in the index: 更好的索引仍然是包含所有相关列的覆盖索引,因此不再需要读取表,因为所有信息都在索引中:

create index idx3 on members (membertype, lname, fname);

As mentioned, the DBMS may still read the full table instead when it assumes that most records will match anyway. 如前所述,当DBMS假定大多数记录仍然匹配时,它仍然可以读取整个表。 Indexes are only an offer to the DBMS which it may use or not. 索引只是DBMS可能使用与否的提议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM