教程 > MySQL 教程 > MySQL 教程 阅读:154

MySQL BETWEEN 条件

可以使用BETWEEN子句来替换“大于等于和小于等于”条件的组合。也就是BETWEEN 表示字段值在给定的两个检索值之间。

BETWEEN 语法

SELECT column_name, function(column_name)
FROM table_name
WHERE column_name  BETWEEN value1 AND value2;

示例

下面我们通过示例来进一步的了解BETWEEN的用法。我们有一张employee_tbl表,数据记录如下:

+------+------+------------+--------------------+
|  id  | name | work_date  | daily_typing_pages |
+------+------+------------+--------------------+
|   1  | John | 2007-01-24 |        250         |
|   2  | Ram  | 2007-05-27 |        220         |
|   3  | Jack | 2007-05-06 |        170         |
|   3  | Jack | 2007-04-06 |        100         |
|   4  | Jill | 2007-04-06 |        220         |
|   5  | Zara | 2007-06-06 |        300         |
|   5  | Zara | 2007-02-06 |        350         |
+------+------+------------+--------------------+
7 rows in set (0.00 sec)

现在,根据上表数据,要获取条件 daily_typing_pages 大于等于 170 且小于等于 300 的记录。这可以使用>=和<=条件完成,如下所示 -

mysql>SELECT * FROM employee_tbl 
   ->WHERE daily_typing_pages >= 170 AND
   ->daily_typing_pages <= 300;

结果如下:

+------+------+------------+--------------------+
|  id  | name | work_date  | daily_typing_pages |
+------+------+------------+--------------------+
|   1  | John | 2007-01-24 |        250         |
|   2  | Ram  | 2007-05-27 |        220         |
|   3  | Jack | 2007-05-06 |        170         |
|   4  | Jill | 2007-04-06 |        220         |
|   5  | Zara | 2007-06-06 |        300         |
+------+------+------------+--------------------+
5 rows in set (0.03 sec)

同样可以使用BETWEEN子句实现如下 -

mysql> SELECT * FROM employee_tbl 
   -> WHERE daily_typing_pages BETWEEN 170 AND 300; 

结果如下:

+------+------+------------+--------------------+
|  id  | name | work_date  | daily_typing_pages |
+------+------+------------+--------------------+
|   1  | John | 2007-01-24 |        250         |
|   2  | Ram  | 2007-05-27 |        220         |
|   3  | Jack | 2007-05-06 |        170         |
|   4  | Jill | 2007-04-06 |        220         |
|   5  | Zara | 2007-06-06 |        300         |
+------+------+------------+--------------------+
5 rows in set (0.03 sec)

查看笔记

扫码一下
查看教程更方便