Sql索引与全表扫描
在编写复杂的 SQL 查询时,我们如何确保使用正确的索引并避免全表扫描?我通过确保只加入具有索引(主键、唯一键等)的列来做到这一点。这够了吗?
While writing complex SQL queries, how do we ensure that we are using proper indexes and avoiding full table scans? I do it by making sure I only join on columns that have indexes(primary key, unique key etc). Is this enough?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
向数据库询问查询的执行计划,然后从那里继续。
不要忘记对 where 子句中出现的列也建立索引。
Ask the database for the execution plan for your query, and proceed from there.
Don't forget to index the columns that appear in your where clause as well.
查看查询的执行计划,了解查询优化器如何认为必须检索内容。该计划通常基于表的统计信息、索引的选择性和连接的顺序。请注意,优化器可以决定执行全表扫描比索引查找“更便宜”。
其他需要注意的事项:
如果可能的话,避免子查询。
尽量减少“OR”谓词的使用
在 where 子句中
Look at the execution plan of the query to see how the query optimizer thinks things must be retrieved. The plan is generally based on the statistics on the tables, the selectivity of the indices and the order of the joins. Note that the optimizer can decide that performing a full table scan is 'cheaper' than index lookup.
other Things to look for:
avoid subqueries if possible.
minimize the use of 'OR'-predicates
in the where clause
很难说什么是最好的索引,因为根据情况有不同的策略。关于索引,您现在仍然应该做一些有趣的事情。
在调整索引时始终尝试分析执行计划。不要害怕尝试。
+
这就是我的全部。
It is hard to say what is the best indexing because there are different strategies depend on situation. Still there are coupe things you should now about indexes.
Always try to analyze execution plan when tuning indexes. Don't be afraid to experiment.
+
That is all from me.
使用数据库优化顾问(SQL Server)来分析您的查询。它将建议添加必要的索引以调整查询性能
Use Database Tuning Advisor(SQL Server) to analyse your query. It will suggest necessary indexes to add to tune your query performance