如何在MySQL表中选择特定值范围?
为了在MySQL表中选择特定范围的值,可以使用WHERE子句。让我们首先创建一个表:
mysql> create table DemoTable ( CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY, CustomerName varchar(200), CustomerAge int, isRegularCustomer bool );
以下是使用insert命令在表中插入一些记录的查询:
mysql> insert into DemoTable(CustomerName,CustomerAge,isRegularCustomer)values('Chris',24,true); mysql> insert into DemoTable(CustomerName,CustomerAge,isRegularCustomer)values('Robert',26,false); mysql> insert into DemoTable(CustomerName,CustomerAge,isRegularCustomer)values('Mike',27,false); mysql> insert into DemoTable(CustomerName,CustomerAge,isRegularCustomer)values('Larry',22,true); mysql> insert into DemoTable(CustomerName,CustomerAge,isRegularCustomer)values('Sam',30,true); mysql> insert into DemoTable(CustomerName,CustomerAge,isRegularCustomer)values('Carol',26,true);
以下是使用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)