笔记之MySQL单表查询select


查询(格式:select 字段名 from 表名;   条件查询:select 字段名 from 表名 where  字段=字段值;)
查询全表:select * from teacher;

查询名字叫玉皇大帝的老师:select * from table where name='玉皇大帝';

列别名:select name as 名字,age as 年龄,sex as 性别 from teacher where name='玉皇大帝';  as的使用,列别名,使用时可以省略,效果不减,as也可以用在表后面将表起别名,如:select t.name,t.age from teacher as t;

消除重复行
distinct,使用时放于select后面,如:select distinct age,sex from teacher;意思是若有数据中的age和sex完全相同,查询只显示一条,若改成*意思就是两条完全相同的数据只留一条

条件查询(等于:=,不等于:!=或><,大于:>,小于:<)
查询name的年龄:select age from teacher where='name';
查询小于30岁的老师:select * from teacher where age<30;(不在30岁用 !=;大于30用>)

逻辑运算(且:and,或:or,非:not,可以把结果翻转)
查询年龄小于20的女学生:select * from student where age<20 and sex='女';

模糊查询(like、%表示任意多个任意字符、_表示一个任意字符)
查询姓孙的学生:select * from student where name like '孙%';

范围查询(in表示在非连续的范围内,between……and……表示在一个连续的范围内)
查询年龄18到20的学生:select * from student where age between 18 and 20,必须小的值在前大的在后;或age<18 and age>20,包含1820,

空判断(null和‘’是不同的,后者意思是空字符,使用null时不能用“=”,要用“is”,null代表什么都没有,如果要查空字符需要用xx='')
查询没有填写身份证的学生:select * from student where card is null;(非null这样写……card is not null)

排序(小到大,即升序asc,大到小,即降序desc)
查询所有学生信息,按照年龄从大到小排序,年龄相同时,再按学号从小到大排序:select * from student order by age desc,stuNo

聚合函数(为快速统计,常用5个聚合函数,count(*)表示计算总行数,括号里写*与列名结果相同,聚合函数不能在where中使用)
总数count;查询所有学生的总数:select count(*) from student ;也可以count(name),其中字段如果有null,则不算在内
最小min;查询女生的最小年龄:select min(age) from student where sex='女'
最大max;查询一班最大年龄:select max(age) from student where class='1班'
总和sum;查询北京学生的年龄总和:select sum(age) student
平均avg;查询女生的平均年龄:select avg(age) from student where sex='女'

分组(group by;select 列1,列2 聚合... from 表名 group by 列1,列2;按字段分组,此字段相同的数据放到一个组;分组后依据会显示结果集中,共多少组就显示几条数据,其他列不显示;可对分组后的数据统计,做聚合运算)
查询各种性别的人数:select sex,count(*) from student group by sex;即按照性别分组后进行统计各组人数和
查询各种年龄的人数:select age,count(*) from student group by age;按年龄分组后统计各组总和
分组后数据筛选(having语法:select 列1,列2,聚合... from 表名 group by 列1,列2,列3... having 列1...聚合...)
查询男生总人数:select age,count(*) from student group by age having sex='男'或不分组select count(*) from student where sex='男'
where是对from后面指定的表进行数据筛选,属于对原始数据的筛选而having是对group by 的结果进行筛选

分页(limit,select * from 表名 limit start count)计算机里默认表里的第一条数据位置为0
每页显示m条数据,问显示第n页的数据:select * from student limit (n-1)*m,m
查询前3行学生信息:select * from student limit 0,3;查询student表中的数据从0开始,显示3条数据

猜你喜欢

转载自www.cnblogs.com/will-wu/p/12717603.html