查询语句不会改变表的记录
一、基本查询
1.字段控制
- 查询所有列
select * from 表名;
- 查询指定列
select 列名1,列名2,from 表名;
- 去除重复行
select distinct 列名 from表名;
- 列运算
1.数量类型的列可以做加减乘除运算
select score*1.5 from student;
2.字符串类型可以做连续运算(连接字符串)
select concat('&',score) from student;
3.转换NULL值 把NULL转换为0
select IFNULL(score,0)+100 from student;
4.给列起别名
select score as 成绩 from student;
select score 成绩 from student;
2.条件控制
1.条件查询
select * from where 限制条件
2.模糊查询
select * from student where name like'王—_';
_匹配任意一个字符
%匹配任意0-N个字符
二、排序
1.升序排列
select * from student order by sage asc;
不写关键字默认是升序排列
2.降序排列
select * from student order by sage desc;
3.使用多列作为排序条件
//当一种条件相同时,没有分出胜负再用第二种条件
select * from student order by sage desc, sname asc;
三、聚合函数
聚合函数用来做某列的纵向查询,而前面的是横向查询
1.count ,计算一列中不为NULL值的个数
select count(sno) from student;
2.max 查询一列中的最大值
select max(score) from student;
3.min 查询一列中的最小值
select min(score) from student;
4.sum 查询一列中数值之和
select sum(score) from student;
5.avg 查询一列中的平均值
select avg(score) from student;
四、分组查询
分组查询是把记录中的某一列进行分组,然后查询组信息
也就是说只能查询分组列
1.查询男生和女生各有多少人
select count(*) from student group by sex;
2.分组前条件
查询大于10岁的男生和女生各有多少人
这里首先先把小于10岁的人去除然后再进行分组
select count(*) from student where sage >10 group by ssex;
3.分组后条件
把分组后满足条件的组筛选出来
查询组内人数大于5人的组
select count(*) from student where sage>10 group by ssex having count(*) >5;
五、limit子句(方言)
limit 用来限定查询结果的起始行,以及总行数
例如查询起始行为第5行,一共查询三行记录
select * from student limit 4,3;
作用:进行分页查询