# 查询条件 where

# where关键字使用位置

select * from `user` where user_code="no1"

where关键字位于表名后面,后面紧跟着各种类型的查询条件

# 各种类型的查询条件

# 字段等于查询条件=

select * from `user` where user_code="no1";
查询user_code为no1的用户数据
select * from `user` where age=32;
查询年龄是32岁的用户数据

# 不等于查询条件--!= <>

select * from `user` where user_code!="no1";
查询user_code不等于no1的用户数据
select * from `user` where age<>32;
查询年龄不是32岁的用户数据

在sql中不等于有2种表示方式 != 或者 <>,这2种方式都是相同的,没有区别

# 大于、小于、大于等于、小于等于--><

select * from `user` where age>32;
查询年龄大于32岁的用户数据
select * from `user` where age<32;
查询年龄小于32岁的用户数据
select * from `user` where age>=32;
查询年龄大于等于32岁的用户数据
select * from `user` where age<=32;
查询年龄小于等于32岁的用户数据

# 区间查询--BETWEEN ... and

查询年龄在32岁到35岁之间的数据
select * from `user` where age>=32 and age<=35
还有一个等价的查询语句
select * from `user` where age between 32 and 35

# 字符串模糊匹配--like

select * from `user` where user_code like "%o1%";
查询user_code中包含o1的用户数据
select * from `user` where user_code like "no%";
查询user_code中no开头的用户数据
select * from `user` where user_code like "%o1";
查询user_code中o1结尾的用户数据
  • like查询有些特殊,like关键字必须搭配%使用,%代表0个或者多个任意字符
  • like查询一般性能比较低,需要谨慎使用
  • like查询还有一个技巧如果user_code字段有索引可以尝试使用no%这种形式可以使用到索引,可以有效提升查询效率

# 包含多个数值的查询--in

select * from `user` where age in(32, 35);
查询年龄是32或者35岁的

# 多个查询条件并列使用的情况

# 多个条件都符合才返回数据

select * from `user` where age>=32 and age<=35

用户的年龄必须满足大于等于32岁并且小于等于35岁

# 多个条件满足任意一个就返回数据

select * from `user` where age>=32 or user_code="no1"

用户的年龄满足大于等于32岁或者user_code="no1",也就是说用户user_code="no1"的情况下,不论年龄是多少都返回该数据

# 多条件混合使用

select * from `user` where age<32 or (user_code="no1" and age>=35)

在多条件混合使用时,把括号内的条件看成一个条件,

上述sql理解成: age < 32 和 user_code="no1" and age>=35两个条件 如果no1年龄在31岁,它不满足user_code="no1" and age>=35, 但是它满足age<32,所以no1这个用户也会返回

如果需要对no1的用户进行特殊处理,那么sql语句要写成

select * from `user` where  (user_code!="no1" and age<32) or (user_code="no1" and age>=35)

上述sql理解成: no1这个用户和其它用户不同,它判断年龄大于35岁才返回,而其它用户小于32岁才返回

# 查询条件中使用字段判断

select * from `user` where  user_code=user_name

查询所有用户中用户编码和用名称相同的数据,这个sql特别之处在于user_code和user_name都是字段名称, 查询结果会对该条数据的这2个字段值进行比较,过滤符合条件数据