SQL - WHERE 条件的顺序是否重要?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3152182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL - Does the order of WHERE conditions matter?
提问by powerboy
Assume that category_id
is an index key (not primary key) of table books
. Is there any difference between the following two SQL statements?
假设这category_id
是 table 的索引键(不是主键)books
。下面两条SQL语句有什么区别吗?
SELECT * FROM books WHERE author='Bill' AND category_id=1
SELECT * FROM books WHERE category_id=1 AND author='Bill'
I guess filtering records first by category_id
and then by author
is faster than filtering them in reverse order. Are SQL engines smart enough to do it this way?
我猜先按category_id
然后按过滤记录author
比按相反顺序过滤记录要快。SQL 引擎是否足够聪明以这样做?
采纳答案by OMG Ponies
No, the order of the WHERE clauses does not matter.
不,WHERE 子句的顺序无关紧要。
The optimizer reviews the query & determines the best means of getting the data based on indexes and such. Even if there were a covering index on the category_id and author columns - either would satisfy the criteria to use it (assuming there isn't something better).
优化器查询并根据索引等确定获取数据的最佳方法。即使 category_id 和 author 列上有一个覆盖索引 - 要么满足使用它的标准(假设没有更好的东西)。
回答by gbn
SQL is declarative.
SQL 是声明性的。
In your example, you have told the engine/optimizer what you want... it will now work out the best way to do that (within reason and "cost" which would be off topic).
在你的例子中,你已经告诉引擎/优化器你想要什么......它现在会找到最好的方法(在合理和“成本”范围内,这将是题外话)。
回答by Dean J
Whereas in general, no, that assumes you're using a modern database. Maybe ten years ago, it certainly mattered then.
而一般来说,不,这假设您使用的是现代数据库。也许十年前,它在那时当然很重要。
回答by ajdams
In short, no, they do not matter as the optimizer will determine the best means for fetching the data.
简而言之,不,它们无关紧要,因为优化器将确定获取数据的最佳方式。
回答by Alex
Yes, SQL is a declarative language. But in SQL Server(not sure about other engines) a DBA can actually (kinda) do this, by forcing an execution plan in SQL Query Store.
是的,SQL 是一种声明性语言。但是在SQL Server(不确定其他引擎)中,DBA 实际上(有点)通过在 SQL 查询存储中强制执行计划来做到这一点。
But, yeah, you can't control it from your app, or from within the query text itself.
但是,是的,您无法从应用程序或查询文本本身控制它。
P.S. 2 more cents: you can control the order of JOIN's by using FORCE ORDER
.
PS 2 美分:您可以使用FORCE ORDER
.