文档介绍:.
SQL基本常用查问语句
--select
select*fromstudent;
--all查问所有
selectallsexfromstudent;
--distin*),sexfromstudentgroupbysex;
按照年纪和性别组合分组统计,并排序
selectcount(*),sexfromstudentgroupbysex,ageorderbyage;
按照性别分组,并且是id大于2的记录最后按照性别排序
selectcount(*),sexfromstudentwhereid>2groupbysexorderbysex;
.
.
查问id大于2的数据,并达成运算后的结果进行分组和排序
selectcount(*),(sex*id)newfromstudentwhereid>2groupbysex*
idorderbysex*id;
--groupbyall所有分组
按照年纪分组,是所有的年纪
selectcount(*),agefromstudentgroupbyallage;
--having分组过滤条件
按照年纪分组,过滤年纪为空的数据,并且统计分组的条数和现实年
龄信息
selectcount(*),agefromstudentgroupbyagehavingageisnotnull;
按照年纪和cid组合分组,过滤条件是cid大于1的记录
selectcount(*),cid,sexfromstudentgroupbycid,sexhavingcid>1;
按照年纪分组,过滤条件是分组后的记录条数大于等于2
selectcount(*),agefromstudentgroupbyagehavingcount(age)>=2;按照cid和性别组合分组,过滤条件是cid大于1,cid的最大值大于2
selectcount(*),cid,sexfromstudentgroupbycid,sexhavingcid>1andmax(cid)>2;
嵌套子查问
子查问是一个嵌套在select、insert、update或delete语句或其他子查
询中的查问。任何允许使用表达式的地方都能够使用子查问。子查问
也称为内部查问或内部选择,而包含子查问的语句也成为外部查问或
.
.
外部选择。
#from(select示table)例
将一个table的查问结果当做一个新表进行查问
select*from(
selectid,namefromstudentwheresex=1
)>2;
上面括号中的语句,就是子查问语句(内部查问)。在外面的是外部
查问,其中外部查问能够包含以下语句:
1、包含惯例选择列表组件的惯例select查问
2、包含一个或多个表或视图名称的惯例from语句
3、可选的where子句
4、可选的groupby子句
5、可选的having子句
示例
查问班级信息,统计班级学生人生
select*,(selectcount(*)fromstudentwherecid=)asnum
fromclassesorderbynum;
#in,notin子句查问示例
查问班级id大于小于的这些班级的学生信息
select*fromstudentwherecidin(
selectidfromclasseswhereid>2andid<4
);
.
.
查问不是班的学生信息
select*fromstudentwherecidnotin(
selectidfromclasseswherename='2班'
)
in、notin后边的子句返回的结果必须是一列,这一列的结果将会作
为查问条件对应前面的条件。如cid对应子句的id;
exists和notexists子句查问示例查问存在班级id为的学生信息
select*fromstudentwhereexists(
select*fr