选择 BETWEEN

你可以使用 BETWEEN 子句替换大于等于且小于等于条件的组合。

数据

+----+-----------+
| `id` | username  |
+----+-----------+
|  1 | admin     |
|  2 | root      |
|  3 | toor      |
|  4 | mysql     |
|  5 | thanks    |
|  6 | java      |
+----+-----------+

查询运算符

SELECT * FROM stack WHERE id >= 2 and id <= 5; 

与 BETWEEN 类似的查询

SELECT * FROM stack WHERE id BETWEEN 2 and 5; 

结果

+----+-----------+
| `id` | username  |
+----+-----------+
|  2 | root      |
|  3 | toor      |
|  4 | mysql     |
|  5 | thanks    |
+----+-----------+
4 rows in set (0.00 sec)

注意

BETWEEN 使用 >=<=,而不是 ><

使用 NOT BETWEEN

如果你想使用负片你可以使用 NOT。例如 :

SELECT * FROM stack WHERE id NOT BETWEEN 2 and 5; 

结果

+----+-----------+
| `id` | username  |
+----+-----------+
|  1 | admin     |
|  6 | java      |
+----+-----------+
2 rows in set (0.00 sec)

注意

不能使用 >< 而不是 >=<= 也就是说,WHERE id NOT BETWEEN 2 and 5WHERE (id < 2 OR id > 5) 相同。

如果你在 BETWEEN 搜索中使用的列上有索引,MySQL 可以使用该索引进行范围扫描。