1、单表查询 2、模糊查询 3、范围查询 4、聚合函数 5、分组查询
1、查询所有数据select * from userinfos2、查询表的部分数据select userid,username,age from userinfos3、给列取别名-- 列名 as 别名 列名 别名 别名=列名select userid as 用户编号,username 用户名,年龄=agefrom userinfos4、排序 desc 降序 asc 升序select userid、username、age from userinfosorder by age asc
--1、% 匹配0个或多个select * from userinfos where username like '%ad%' --查询所有包含ad的select * from userinfos where username like '%d(a%)' --查询以什么开头或什么结尾--2、_ 匹配单个字符,限制表达式的字符长度select * from userinfos where like '_dmin' --查询长度为5,后四位为dmin的数据select * from userinfos where like '_____'--3、[]范围匹配,括号中字符中的一个select * from userinfos where like 'ad[mnp]in'select * from userinfos where like 'ad[m|n|p]in'select * from userinfos where like 'ad[m-p]in'--4、[^]不在括号范围之内的单个字符select * from userinfos where like 'ad[^abc]in'
--select * from test where 子句 条件--给定范围--比较运算符 > < >= <= <>select * from userinfos where age>30--in、not inselect * from userinfos where age in(30,23,34)select * from userinfoswhere deptid in(select deptid from deptinfos --子查询)--between and 等价于 >= and <= betweent and 效率更高select * from userinfoswhere age between 20 and 31 --age>=20 and age<=31--查询前面多少条,百分比select top 10 * from userinfosselect 100 percnet * from userinfos
--聚合函数:对一组值执行计算并返回单一的值count 记录数 计算null值 经常与select语句中的group by 结合使用 count(1)比count(*)效率高--五种聚合函数count 记录个数sum 求和avg 平均值max 最大值min 最小值--countselect count(1) record from userinfos--sumselect sum(age) from userinfos--ageselect avg(age) from userinfos--maxselect max(age) from userinfos--minselect min(age) from userinfos
--分组查询select ...where ...group by--统计各个部门的用户数select deptid,count(1) 用户数 from userinfosgroup by deptidselect deptid,count(1) 用户数 from userinfoswhere age>30group by deptidhaving deptid>1 --分组后刷选order by deptid--注意:select之后出现的列必须要包含在聚合函数之中或group by之后,--只针对出现group by 的情况,不然会报错
