测牛学堂:软件测试要会的sql语法总结之sql查询where条件判断

77 阅读1分钟

查询部分字段数据

我们在实际查询过程中,很少使用* 去查询所有的字段。

通常使用的是查询部分字段的方法

字段名之间是用英文逗号隔开

select 字段1,字段2, ... from 表名

select name,sex,age from students

给字段和表起别名

1 给表起别名, 给表后面加as ,注意查询的字段都要别名.xxx才可以

select s.name,s.age from student as s

2 字段取别名

select name as 姓名,sex as 性别 from students

查询字段去重

关键字是DISTINCT

select DISTINCT sex from students

条件查询详解

where是查询的条件语法,where支持多种运算符进行条件处理。

比较运算

等于 = ,小于 < ,大于> ,大于等于>=,小于等于 <=, 不等于:!=

select age from students where age <18

逻辑运算

逻辑运算符有三个 and,or,not,通过逻辑运算符可以连接多个查询条件,他们之间准寻的是或,且,非的关系

1or使用:查询所有女生或者年龄小于18的

select name from students where sex='女' or age<18

2 not 使用:查询所有不是北京的学生:

select name from students where not city='北京'

3 and使用:查询所有年龄大于18 的女生

select name from students where sex='女'and age > 18

模糊查询

关键字like,两个重要符号

1 % 匹配任意多个字符

2 - 匹配任意一个字符

例1:查询姓孙的学生

select * from students where name like '孙%'

例2:查询姓名中包含小字的学生

select * from students where name like '%小%'

范围查询

范围查询有两个,

1 in 表示在一个非连续的范围内

例1:查询年龄是18,21的学生

select * from students where age in (18,21)

2 between ... and ... 表示在一个连续的范围内

例1:查询年龄是15~20岁之间的学生

select * from students where age between 15 and 20

空判断

在mysql中,空表示为null ,和' '字符是不一样的概念。

1 判断为空:is null

2 判断非空 is not null

select * from students where name is null