1.模糊查询用:LIKE
2.通配符:
1.%
2.[ ]
3._
4.^
注:“ ^ ”通配符只能用在[ ]里,必须和[ ]搭配使用,“ ^ ”通配符不是标准的SQL通配符,只是MS SQL Server支持的,其他的DBMS不支持这种通配符,我们优先使用not like.
3.%通配符——匹配0-n个任意字符
--查询所有姓张的学生信息
select * from TbStudent where stuName like '张%';
--查找:名字里有'三'的学生信息
select * from TBStudent where stuName like '%三%';
--查找:名字里没有'三'的学生信息
select * from TBStudent where stuName not like '%三%';
select * from TbStudent where stuName like ‘%^敏%’; ——这样不行不能匹配
4._通配符——表示匹配任意一个字符
--查找:姓‘张’,并且名字只有一个字的人
select * from TbStudent where stuName like '张_';
--也可以
select * from TbStudent where stuName like '张%' and len(stuName)=2;--LEN函数统计长度
5.[ ]通配符——表示匹配一定范围内的,任意一个字符
--查询:姓'张'或者姓‘鲁’的所有记录
select * from TbStudent where stuName like '张%' or stuName like '鲁%';--第一种
select * from TbStudent where stuName like '[张鲁]%';--第二种
select * from TbStudent where stuName like '[张,鲁]%';--第三种
--练习:查询12-14级所有学生信息
select * from TbStudent where stuNumber like '1[2,3,4]%';
select * from TbStudent where stuNumber like '1[2-4]%';
错误写法:select * from TbStudent where stuNumber like ‘[12,13,14]%’;
通配符[ ],永远只能去匹配一个字符
6.^通配符
--查询,不是14级的学生
select * from TbStudent where stuNumber not like '14%';
select * from TbStudent where stuNumber like '1[^4]%';
--^通配符:必须用在[]里,也就是必须和通配符[]搭配使用
--练习:查询名字里没有'三'字的学生
select * from TbStudent where stuName not like '%三%';
select * from TbStudent where stuName like ‘%[^三]%’;——错误写法
7.聚合函数 max(),min(),avg(),sum(),count(),常用的有五种
--求平均值
select avg(stuage) from TbStudent;
--求最大值
select max(stuAge) from TbStudent;
--求和sum()
select sum(stuAge) from TbStudent;
--count()统计记录条数
select count(*) from TbStudent;
select count(stuId) from TbStudent;
select count(1) from TbStudent;
select count(stuAge) from TbStudent;
count ()字段如果为空,是不会被计算在内
avg()时,如果有记录在该字段上为null,这条记录是不会统计在内
8.空值查询
--如果判断一个字段的值是不是null,需要使用is 关键字,不能使用等号
select * from TbStudent where stuAddress is null;
--查询籍贯不是null的所有同学
select * from TbStudent where stuAddress is not null;
9.ISNULL(原始数据,代替值)函数
--注意:not like, is not
--查询所有学生信息,如果籍贯是null,就用‘未知’替代
select stuName,stuNumber,isnull(stuAddress,'未知') from TbStudent;
---查询所有数学成绩为null的学生
select * from TbStudent where stuMath is null;
–查询所有学生的考试成绩,如果为null,则用‘缺考’代替
select stuName,stuNumber,isnull(stuMath,‘缺考’) from TbStudent;
这样会出现错误,stuMath是smallint类型 ‘缺考’是varchar类型,不允许填充在同一列上
注:数据表中的任何一列,都只能存储一种数据类型的数。
SQL里的null和C#中的null不是一样的,C#里的null:表示一个引用类型的变量,不指向堆上的任何对象
SQL里的null:unknown,表示不知道,SQL里的任意数据类型的字段,都可以赋值为null,
--SQL里的null与任何数据做运算,结果还是null
--查询所有学生的数学成绩,并且给所有人的数学成绩+10分
select stuName,stuNumber,stuMath+10 as '数学' from TbStudent;
select stuName,stuNumber,isnull(cast(stuMath as varchar(4)),'缺考') from TbStudent;
--cast数据类型转换,这个isnull()函数,不会修改原表中的数据,只是改变了查询结果中的显示方式