【问题标题】:Increasing conditions in WHERE clause will increas the search speed?在 WHERE 子句中增加条件会提高搜索速度吗?
【发布时间】:2015-12-27 17:03:00
【问题描述】:

我有一张这样的桌子:

// mytable
+----+-------+---------+
| id | name  |   code  |
+----+-------+---------+
| 1  | jack  | 1       |
| 2  | acton | 1       |
| 3  | aiken | 1       |
| 4  | peter | null    |
| 5  | ash   | null    |
| 6  | fabia | 2       |
| 7  | ubon  | null    |
| 8  | taavi | null    |
| 9  | wade  | 2       |
| 10 | ian   | 1       |
+----+-------+---------+

我想选择其id 为 4 的行。这是我的查询:

select * from mytable where id = 4

我还知道code 该行的值是null。现在我想知道,如果我添加这个... and code = null会提高搜索速度吗?

【问题讨论】:

  • 您提议的更改将返回零行。使用is null。表上有哪些索引?假设 id 上的唯一索引,这个额外的检查可能会稍微减慢速度。
  • @Shafizadeh 如果 id 是唯一的并且代码被索引,添加“... and code is null”不会有任何区别,只会使用 id 索引

标签: mysql performance search


【解决方案1】:

如果你添加:

and code = null

那么您将不会返回任何行,因为= null 总是返回null。而where 会过滤掉值不正确的行。

相反,您应该:

and code is null

大概,id 上面有一个索引(所有主键都有一个索引)。如果是这样,SQL 引擎可能会在获取该行之后再进行一次比较,以确保code 匹配条件。考虑到获取数据的所有其他工作,这非常非常微不足道。包括附加条件很可能对性能没有明显影响。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 2013-12-23
    • 2020-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多