过滤数据
使用WHERE语句
在select语句中,数据根据where子句中指定的搜索条件进行过滤。
mysql> select prod_name,prod_price from products where prod_price = 2.50;
+---------------+------------+
| prod_name | prod_price |
+---------------+------------+
| Carrots | 2.50 |
| TNT (1 stick) | 2.50 |
+---------------+------------+
2 rows in set (0.09 sec)
在实际应用中,数据也可以在应用层进行过滤,为此目的,SQL的select语句为客户机应用检索出超过实际
所需的数据,然后客户机代码对返回数据进行处理,通常这样不太好,因此通常有可能的情况下,会在数据库中
完场数据过滤。
where 子句操作符
操作符 | 说明 |
---|---|
= | 等于 |
< > | 不等于 |
!= | 不等于 |
< | 小于 |
<= | 小于等于 |
> | 大于 |
>= | 大于等于 |
BETWEEN | 在指定的两个值之间 |
检查单个值
mysql> select prod_name,prod_price from products where prod_name = 'fuses';
+-----------+------------+
| prod_name | prod_price |
+-----------+------------+
| Fuses | 3.42 |
+-----------+------------+
1 row in set (0.00 sec)
注意: mysql执行不区分大小写,因此 fuses和Fuses匹配。
mysql> select prod_name,prod_price from products where prod_price<10;
+---------------+------------+
| prod_name | prod_price |
+---------------+------------+
| .5 ton anvil | 5.99 |
| 1 ton anvil | 9.99 |
| Carrots | 2.50 |
| Fuses | 3.42 |
| Oil can | 8.99 |
| Sling | 4.49 |
| TNT (1 stick) | 2.50 |
+---------------+------------+
7 rows in set (0.01 sec)
mysql> select prod_name,prod_price from products where prod_price<=10;
+----------------+------------+
| prod_name | prod_price |
+----------------+------------+
| .5 ton anvil | 5.99 |
| 1 ton anvil | 9.99 |
| Bird seed | 10.00 |
| Carrots | 2.50 |
| Fuses | 3.42 |
| Oil can | 8.99 |
| Sling | 4.49 |
| TNT (1 stick) | 2.50 |
| TNT (5 sticks) | 10.00 |
+----------------+------------+
9 rows in set (0.00 sec)
不匹配检查
mysql> select prod_name,prod_price from products where vend_id<>1003;
+--------------+------------+
| prod_name | prod_price |
+--------------+------------+
| .5 ton anvil | 5.99 |
| 1 ton anvil | 9.99 |
| 2 ton anvil | 14.99 |
| Fuses | 3.42 |
| Oil can | 8.99 |
| JetPack 1000 | 35.00 |
| JetPack 2000 | 55.00 |
+--------------+------------+
7 rows in set (0.01 sec)
注意:单引号用来限定字符串,如果将值与串类型的列进行比较,则需要限定引号,用来与数值列进行比价则
不需要引号。
检查值范围
mysql> select prod_name,prod_price from products where prod_price between 5 and 10;
+----------------+------------+
| prod_name | prod_price |
+----------------+------------+
| .5 ton anvil | 5.99 |
| 1 ton anvil | 9.99 |
| Bird seed | 10.00 |
| Oil can | 8.99 |
| TNT (5 sticks) | 10.00 |
+----------------+------------+
5 rows in set (0.11 sec)
注意:between所指定的匹配范围内的值,已包括开始值和结束值。
空值检查
NULL 无值,它与字段包含0、空字符串或仅仅包含空格不同。
select prod_name from products where prod_price IS NULL;
注意:在通过过滤选择出不具有特定值的行时,可能希望返回具有NULL的行,但是,不行,因为位置具有特殊含义
,数据库不知道是否匹配,所以在匹配过滤或者不过滤时不返回他们。