1.单表查询步骤简例:
a.选择库 use 库名(可省略)
b.选择表 from 表名
c.选择字段 如,name,且值为张三 where name='张三'
d.查看结果 select *(展示的字段),或select name,sex,years
转化为sql语句如下:
select name,sex,years from student where name='张三'
2.单表查询语法
1)查看----select
a.选择显示全部字段
select * from student;
选择显示部分字段
select name,years,sex from student;
b.修改列的别名---as
select name as '姓名' from student;
c.去重显示---distinct---不建议后面添加多个字段名
select distinct name as '姓名' from student
d.聚合函数
见下面。
2)条件筛选----where
a.精确查询---‘=’
例如:选择姓名为张三的学生信息
select * from student where name='张三';
b.模糊查询---like,需要与'%'或'_'组合使用
例如:查询姓张的学生信息
select * from student where name like '张%'------------查询出的数据,姓名为张三,张丽丽
select * from student where name like '张_'------------只能查询出姓名为张三的数据
例如:查询姓名中带“四”的学生信息
select * from student where name like '%四%'
“%”:代表任意字符,允许为空
“_”:代表任意一个字符,不允许为空
c.或---or
例如:选择姓名为张三或者李四的学生信息
select * from student where name='张三' or name='李四';
d.且---and
例如:选择姓名为张三且年龄为13岁的学生信息
select * from student where name='张三' and years=13;
e.-----"in"
例如:选择来自河北,天津,南京,江苏的学生信息
select * from student where place='河北' or place='天津' or place='南京' or place='江苏'
select * from student where in ('河北','天津','南京','江苏')
f.非,不等于----
select * from student where name like '张%' and place !='河北'
select * from student where name like '张%' and place <> '河北'
select * from student where name not like '张_' and place='河北'
select * from student where place not in('河北','天津','南京')
g.比较-----> >= < <=
例如:查询成绩大于60分的学生姓名
select name from student where score>60
h.查询为空的记录
select * from student where place is null;
select * from student where place is not null;---不为空
i.区间运算-----字段名 between 开始 and 结束
例如:查询分数在60-80之间的学生
select * from student where score between 60 and 80
3)排序---order by
语法:order by 字段名 asc--------升序,不写时默认为升序
order by 字段名 desc -----降序
例如:按照成绩从高到低查询学生信息
select * from student order by score desc
4)聚合函数-----count(*),max(字段名),min(字段名),avg(字段名),sum(字段名)
a.查询记录总数----count(*)
例如:查询本张表总行数---总人数
select count(*) as '总人数' from student;
例如:查询姓张的人数
select count(*) from student where name like '张%'
b.平均值-----avg(字段名)
例如:查询本班学生平均成绩
select avg(score) as '平均成绩' from student
select avg(price * number) as '平均价格' from pen
c.求和---sum(字段名)
例如:求本班所有人总分
select sum(score) from student;
d.求最大值----max(字段名),求最小值---min(字段名)
例如:查询本班最高分和最低分人姓名
select name as 最高分人,max(score)from student
select name as 最低分人,min(score) from student
5)分组-----ground by
a.简例步骤:统计本班优秀(分数>90)男女生各多少人
①找表:from 表名
②找参与分组的记录:where score>90
③以什么字段分组:ground by sex------找分组字段时,主要观察,数据信息的哪个字段是共同的
④统计每组结果:select count(*)
转换为sql语句:select count(*) as 人数 from student where score>90 ground by sex;
6)分组后信息筛选---having
having----分组完成条件,经常加聚合函数。必须有ground by才能有having。满足having后条件的组才可以留下;
where----分组前条件,满足where之后才可以参与分组;
例如:显示两门以上课程不及格的学生
select count(*) from student where score <60 ground by name having count(*)>2
7)选择确定行数的部分记录----limit n,m:从第n+1条开始,往后取m条
例如:去本次成绩的第5到第十名
select name as 姓名,score as 分数 from student order by score desc limit 4,5;
备注:在建表,定义字段名变量时,不要使用数据库敏感单词。如本文使用的name。