模糊查询
主要是通过通配符进行查询。通配符主要有like、%、[]、_
%通配符
匹配任意多个任意字符,类似于正则表达式中的.
操作 。在使用的时候,需要搭配like
进行使用。
//在student表中查询姓张的同学
select *from student where name like N'张%' //中文前面最好加上N
//在student表中查询名字中包含张的同学
select *from student where name like N'%张%'
[]通配符
[]搭配%使用,表示%不再是一个通配符,而是一个字符。
//查找名字为张_李的学生
select *from student where name like '张[%]李'
_通配符
表示任意字符,类似于%
的操作,%
表示任意字符可以出现任意次数,_
表示 任意字符只能出现一次。只能出现一次,不能出现连续的两个及以上。
//查找名字为两个字并且姓张的学生
select *from student where name like N'张_'
空值处理
在数据库中null才表示为空。空值不能使用运算符进行查询。在数据库中null表示为一个unknow的值。通常使用is
进行查询。
null与其他值进行运算的时候,结构都是null
select *from student where name = null //错误写法
select *from student where name is null//正确书写
注意:isnull()为一个函数,上面使用空值处理需要中间加一个空格。
数据排序
- order by子句位于select语句末尾,可以按照多列进行排序,排序的条件之间用逗号隔开。
asc
升序,desc
降序,默认按照升序进行排序
//在score表中,首先按照英语成绩进行排序,如果英语成绩相同,则按照数学进行排序
select *from score order by english desc, math desc
group by分组
//查询每个班中男同学的人数及班级ID
select 班级Id = classId
男同学人数=count(*)
from student
where sex = '男'
group by classId
在使用group函数时,进行查询的语句必须包含在分组的列中,如果不存在则需要通过聚合函数进行包含起来
//错误,由于age是没有包含在分的组中,因此需要加上一个聚合函数搭配使用
select classId,count(name),age
from student
group by classId
having关键字
- 在分组之后,对于一些内容需要进行保留,对于一部分不需要进行保留,所以需要对内容进行筛选。having就是在分组之后,对组进行筛选。
//查询班级人数大于20的班级Id,及人数
select
classId as 班级Id
count(*) as 班级人数
*from student
group by classId
having count(*) > 20