格式:
select <目标列名序列> ---需要哪些列
from <表名> ---来自于哪些表
where <行选择条件> ---根据什么条件
group by <分组依据列>
having <组选择条件>
order by <排序依据列>
select * from student
select * from student where sno = ‘1‘
select * from student s,course c,score sc where sc.`sno` = s.`sno` and sc.`cno` = c.`cno`
select distinct * from score //去掉查询结果的重复行
select * from student where sage between 20 to 25 //查询20~30岁之间的学生信息
select * from student where sage not between 20 to 25 //查询不是20~30岁之间的学生信息
select * from student where sdept in (‘计算机系‘,‘管理系‘,‘外语系‘)//查询计算机系、外语系、管理系的学生名单
select * from student where sdept not in (‘计算机系‘,‘管理系‘)//查询不是计算机系、管理系的学生名单
迷糊查询:
关键字 like
_ 表示匹配任意一个字符
% 表示配备0个或多个字符
[]表示匹配[]中任意的字符
[^]表示不匹配[]中任意的字符
select * from student where sname = ‘王%‘ //表示查询全部姓王的同学的信息
select * from student where sname = ‘王_‘//表示查询姓王且名字只要两个字的同学的信息
select * from student where sname = ‘王__‘//表示查询姓王且名字只要三个字的同学的信息
select * from student where sname = ‘[赵钱孙李]%‘ 表示查询姓赵钱孙李的同学的信息
转义字符:
关键字:ESCAPE
select * from sumbit where filed1 like ‘%30!%%‘ ESCAPE ‘!‘ //查询包含有字符串‘30%‘的记录
select * from submit where filed like ‘%!_%‘ escape ‘!‘ //查询包含有字符串‘_‘的记录
涉及空值的查询:
select * from score where grade is null //查询成绩为空的信息
select * from score where grade is not null //查询成绩不为空的信息
多重查询:
select * from student where (sdept = ‘计算机系‘ or sdept = ‘管理系‘) and sage < 25
对查询结构进行排序:
关键字:order by ...排序依据的列
desc ...//降序排列
asc...//升序排列(默认)
select * from student order by sage AES //查询学生信息以年龄为依据进行降序排列
聚合函数查询:
关键字:count、sum、avg、max、min
*注意:聚合函数不能出现在where子句中
select avg(grade) 平均分 from score where sno = ‘1‘ //查询学号为1 的同学的平均分
分组查询:
关键字 group by ... (having....)having(并且的意思)
SELECT sno 学号,AVG(grade) 平均分 FROM score GROUP BY sno ORDER BY 平均分 DESC //查询按学号分组的学生的平均分并以平均分的从高到低排序
SELECT sdept 系别 ,COUNT(sno) 人数 FROM student GROUP BY sdept ORDER BY 人数 DESC //查询各系的学生数量
SELECT sdept 系别,ssex 性别,COUNT(ssex) 人数 FROM student GROUP BY sdept,ssex ORDER BY sdept//查询各系性别的人数
SELECT sno,AVG(grade) 平均成绩 FROM score GROUP BY sno HAVING 平均成绩 > 90
SELECT sno ,AVG(grade) 平均成绩 FROM score sc GROUP BY sno