如何在 MySQL 表中选择特定值范围?


为了在 MySQL 表中选择特定值范围,可以使用 WHERE 子句。让我们首先创建一个表

mysql> create table DemoTable
(
   CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   CustomerName varchar(200),
   CustomerAge int,
   isRegularCustomer bool
);
Query OK, 0 rows affected (0.57 sec)

以下是使用 insert 命令在表中插入一些记录的查询

mysql> insert into DemoTable(CustomerName,CustomerAge,isRegularCustomer)values('Chris',24,true);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(CustomerName,CustomerAge,isRegularCustomer)values('Robert',26,false);
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable(CustomerName,CustomerAge,isRegularCustomer)values('Mike',27,false);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(CustomerName,CustomerAge,isRegularCustomer)values('Larry',22,true);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(CustomerName,CustomerAge,isRegularCustomer)values('Sam',30,true);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(CustomerName,CustomerAge,isRegularCustomer)values('Carol',26,true);
Query OK, 1 row affected (0.16 sec)

以下是使用 select 命令显示表中记录的查询

mysql> select *from DemoTable;

这将产生以下输出

+------------+--------------+-------------+-------------------+
| CustomerId | CustomerName | CustomerAge | isRegularCustomer |
+------------+--------------+-------------+-------------------+
|          1 | Chris        |          24 |                 1 |
|          2 | Robert       |          26 |                 0 |
|          3 | Mike         |          27 |                 0 |
|          4 | Larry        |          22 |                 1 |
|          5 | Sam          |          30 |                 1 |
|          6 | Carol        |          26 |                 1 |
+------------+--------------+-------------+-------------------+
6 rows in set (0.00 sec)

以下是选择 MySQL 表中特定值范围的查询。在这里,我们选择年龄大于或等于 24 且小于或等于 27 的客户记录。此外,客户应为常规客户,即“isRegularCustomer”列下值为 1

mysql> select CustomerId,CustomerName,CustomerAge,isRegularCustomer from DemoTable
where isRegularCustomer=true AND CustomerAge >=24 AND CustomerAge <= 27;

这将产生以下输出

+------------+--------------+-------------+-------------------+
| CustomerId | CustomerName | CustomerAge | isRegularCustomer |
+------------+--------------+-------------+-------------------+
|          1 | Chris        |          24 |                 1 |
|          6 | Carol        |          26 |                 1 |
+------------+--------------+-------------+-------------------+
2 rows in set (0.00 sec)

更新于: 30-7-2019

663 浏览

开启你的 职业

通过完成课程获得认证

开始
广告