《MySQL必知必会》过滤数据,数据过滤(where ,in ,null ,not)

时间:2022-06-07 17:57:50

《MySQL必知必会》过滤数据,数据过滤

1、过滤数据

1.1 使用 where 子句

在SEL ECT语句中,数据根据WHERE子句中指定的搜索条件进行过滤。

WHERE子句在表名(FROM子句) 之后给出,如下所示:

select *
from orders
where Date(order_date) = '2005-09-01';

《MySQL必知必会》过滤数据,数据过滤(where ,in ,null ,not)

需要注意的是,不仅SQL有数据过滤,在实际开发中,应用层也会有数据过滤。但是通常这样是不能令人满意的。

因此要对数据库进行优化,以便快速有效地对数据进行过滤,让应用层去解决数据过滤,这将会影响到应用的性能。并且使所创建的应用完全不具备可伸缩性。此外,如果在客户机上过滤数据,服务器不得不通过网络发送多余的数据,这将导致网络带宽的浪费。

总之,提高数据库的性能,也是开发中非常重要的一部分。

WHERE子句的位置在同时使用ORDER BY和WHERE子句时

应该让ORDER BY位于WHERE之后,否则将会产生错误。

1.2 where子句操作符

操作符 说明
= 等于
<> 不等于(推荐使用)
!= 不等于
< 小于
<= 小于等于
> 大于
>= 大于等于
between 在指定两值区间内
select order_date
from orders
where Date(order_date) <> '2005-09-01';

《MySQL必知必会》过滤数据,数据过滤(where ,in ,null ,not)

SELECT prod_name,prod_price
FROM products
WHERE prod_price BETWEEN 5 AND 10;

《MySQL必知必会》过滤数据,数据过滤(where ,in ,null ,not)

其他语句,可以自行尝试编写执行。

这里需要特别注意的是,空值查询

select cust_name , cust_email
from customers
where cust_email is null;

《MySQL必知必会》过滤数据,数据过滤(where ,in ,null ,not)

这里返回的数据,只包括查询字段为空值的数据。

那么,is not null 查出来的数据将会是怎么样的呢?

select cust_name , cust_email
from customers
where cust_email is not null;

《MySQL必知必会》过滤数据,数据过滤(where ,in ,null ,not)

所有的非空值都会匹配。

同时,注意null 值是不会作为不匹配数据被查询出来。

《MySQL必知必会》过滤数据,数据过滤(where ,in ,null ,not)

现有数据如上。

select cust_name , cust_zip
from customers
where cust_zip <> '88888';

《MySQL必知必会》过滤数据,数据过滤(where ,in ,null ,not)

null 值的数据将被不匹配查询过滤,因为数据库也不知道它是否匹配,对于数据库来说,它是未知的,是有特殊含义的。

2、 数据过滤

2.1 组合where子句

可以用 and 和 or 关键字,组合 where 子句。

select  order_date
from orders
where year(order_date) = 2005 and month(order_date) = 9;

《MySQL必知必会》过滤数据,数据过滤(where ,in ,null ,not)

select  order_date
from orders
where year(order_date) = 2005 or month(order_date) = 9;

《MySQL必知必会》过滤数据,数据过滤(where ,in ,null ,not)

这里有一个and 和 or 执行优先级的问题。

select  order_num,order_date
from orders
where year(order_date) = 2005 and month(order_date) = 9 or cust_id = 10001;

《MySQL必知必会》过滤数据,数据过滤(where ,in ,null ,not)

由上面的查询结果,可知,DBMS 先处理 and 操作符,再处理 or 。and 的优先级 > or 。

还可以使用圆括号来制定优先处理。

select  order_num,order_date
from orders
where year(order_date) = 2005 and ( month(order_date) = 9 or cust_id = 10001 );

《MySQL必知必会》过滤数据,数据过滤(where ,in ,null ,not)

不要过分依赖计算次序。复杂的 and 部分用圆括号也是可以的,虽然并未改变计算顺序,但是能消除歧义,便于阅读,这间接方便了后期维护,这是值得推崇的。

2.2 IN 操作符

IN 操作符用来指定条件范围,在指定范围内对每个条件进行匹配。(注意与between 的用法区分开来, between 表示匹配区间范围内的值)

SELECT prod_name,prod_price
FROM products
WHERE prod_price in (10 , 13, 50);

《MySQL必知必会》过滤数据,数据过滤(where ,in ,null ,not)

IN 是具有和 or 相同的功能,但是 IN 有着他自身的优点。

  • 在使用长的合法选项清单时,IN操作符的语法更清楚且更直观
  • 在使用IN时, 计算的次序更容易管理(因为使用的操作符更少)。
  • IN操作符- -般比0R操作符清单执行更快
  • IN的最大优点是可以包含其他SELECT语句,使得能够更动态地建立WHERE子句。第14章将对此进行详细介绍。

2.3 NOT 操作符

select cust_name , cust_email
from customers
where cust_email is not null;

《MySQL必知必会》过滤数据,数据过滤(where ,in ,null ,not)

所有的非空值都会匹配。

MySQL中的NOT MySQL支持使用NOT对IN、BETWEEN和EXISTS子句取反,这与多数其他DBMS允许使用NOT对各种条件取反有很大的差别。