mysql必知必会-简单查询-2

简单查询

过滤数据

  • 使用where子句

数据库一般很少需要检索表中所有的行,通常只会根据特定的需求提取表数据的子集,而检索表中所需的特定数据则需要指定搜索条件(也称为过滤条件)。

在select语句中,数据根据where子句中指定的搜索条件进行过滤,where子句在表名(from子句)之后给出,基本结构如下:

select 字段名 from 表名 where 字段名=特殊值;

备注:在同时使用order by 和 where 子句时,应该让order by 位于where之后,否则会产生错误

  • where子句操作符
操作符 说明
= 等于
<> 不等于
!= 不等于
< 小于
<= 小于等于
> 大于
>= 大于等于
between 在指定的两个值之间
  • 检索单个值
select prodouct_name  
from products
where prodouct_id = 1;
#检索产品编号为1的产品名称
select prodouct_name,prodouct_price  
from products
where prodouct_price > 10;
#检索产品价格大于10的产品名称
  • 不匹配检查
select vend_id,prodouct_name
from products
where vend_id <> 1003;
#检索vend_id不是1003的产品名称

另一种等价搜索方法

select vend_id,prodouct_name
from products
where vend_id != 1003;
#检索vend_id不是1003的产品名称
  • 范围值检查

为了检查某个范围的值,可以使用between操作符
基本格式:

select 字段名 from 表名 where 字段名 between 值1 and 值2;

select prodouct_name,product_price
from products
where product_price between 10 and 30;
#检索价格处于10到30之间的所有产品
  • 空值检查

select语句使用一个特殊的where子句来检查某字段是否具有null值

select 字段名 from 表名 where 字段名 is null;

数据过滤

  • 组合where子句

前面介绍的都是单一条件过滤,本部分将介绍如何使用and子句或者or子句的方式来实现多条件过滤

  • and操作符
select prodouct_name,prodouct_price  
from products
where prodouct_price > 10 and vend_id = 3;
#检索vend_id=1003且价格大于10的产品名称
  • or操作符
select prodouct_name,prodouct_price  
from products
where prodouct_price > 10 or vend_id = 3;
#检索vend_id=1003或者价格大于10的产品名称
  • 计算次序

and的优先级要高于or

select prodouct_name,prodouct_price  
from products
where  vend_id = 2 or vend_id = 3 and  prodouct_price > 10;
#系统是默认先执行and 后执行or的 因此本次操作的条件逻辑会是vend_id等于2的任何产品 或者 vend_id等于3且大于10的产品
# vend_id = 2 or (vend_id = 3 and  prodouct_price > 10)

如果需要选择的是vend_id = 2 or vend_id = 3的产品中 价格大于10的产品 则需要使用括号来改变执行顺序

select prodouct_name,prodouct_price  
from products
where ( vend_id = 2 or vend_id = 3) and  prodouct_price > 10;
  • in操作符

圆括号在where子句中还有另一种用法,in操作符用来指定条件范围,范围中的每个条件都可以进行匹配。in取合法值的由逗号分隔的清单,全都括在圆括号内

elect prodouct_name,prodouct_price  
from products
where vend_id in( 2,3) and  prodouct_price > 10;
#等价于上面的例子
  • not操作符

where子句中的not操作符有且只有一个功能,就是否定它之后所跟的任何条件

elect prodouct_name,prodouct_price  
from products
where  vend_id not in( 2,3) 
#检索 vend_id 不是2或者3的所有产品名及价格

猜你喜欢

转载自blog.csdn.net/weixin_43462709/article/details/83995616