1.where和having的区别
1)定义
where:
where是一个约束声明,使用where来约束来自数据库的数据;
where是在结果返回之前起作用的;
where中不能使用聚合函数。
having:
having是一个过滤声明;
在查询返回结果集以后,对查询结果进行的过滤操作;
在having中可以使用聚合函数。
2)执行顺序
where早于 having
where子句在聚合前先筛选记录,也就是说作用在group by 子句和having子句前,而having子句在聚合后对组记录进行筛选
3)where不能使用聚合函数、having中可以使用聚合函数
筛选出北京西城、东城、海淀及各区学校数量
SELECT region,count(school)FROM T02_Bejing_schoolWHERE region IN ('海淀' , '西城' , '东城') GROUP BY region;
筛选出北京西城、东城、海淀三个区中学校数量超过10所的区及各区学校数量。
SELECT region,count(school)FROM T02_Bejing_schoolWHERE region IN ('海淀' , '西城' , '东城')GROUP BY region HAVING count(school) > 10;
注意!我们不能用where来筛选超过学校数量超过10的区,因为表中不存在这样一条记录。
而HAVING子句可以让我们筛选成组后的各组数据。
2.MySQL中<=>操作符和=的区别
相同点
像常规的 = 运算符一样,两个值进行比较,结果是0(不等于)或1(相等);换句话说:A <=> B 得0 和 a <=> a 得1。
不同点
和=运算符不同的是,NULL的值是没有任何意义的。所以=号运算符不能把NULL作为有效的结果。所以:请使用<=>,a <=> NULL 得0, NULL<=> NULL 得出 1。和 = 运算符正相反,=号运算符规则是 a =NULL 结果是NULL ,甚至NULL = NULL 结果也是NULL。顺便说一句,mysql上几乎所有的操作符和函数都是这样工作的,因为和NULL比较基本上都没有意义。
3、作业

检索 中文的时候 加 ‘’单引号
select from text where addr=’北京’;
1、查询所有学生的信息
select from text;
2、查询姓名是李白的学生信息
select from text where name=’李白’;
3、查询1班是上海的学生
select from text where class=’1班’ and addr=’北京’;
4、查询家乡是北京或者上海的学生
select from text where addr<=>’北京’ || addr<=>’上海’;
5 、查询小乔的年龄
select name,age from text where name=’小乔’;
6、查询家乡不在北京的学生
select from text where addr<>’北京’ or addr is null;
7、查询年龄小于20的女同学
select from text where age<20 and sex='女';
8、查询年龄为18至20的学生
select from text where age between 18 and 20;
10、查询女生的平均年龄
select sex,avg(age) from text where sex=’女’;
select sex,round(avg(age),2) from text where sex=’女’;
11、查询姓名包含白的学生
select from text where name like’%白%’;
12、查询所有学生信息,按年龄从大到小排序,年龄相同时,再按学号从小到大序
select from text order by age desc,id;
13、查询女生的最大年龄
select sex,max(age) from text where sex=’女’;
14、查询北京同学的年龄总和:
select addr,sum(age) from text where addr=’北京’;
15、查询各种性别的人数:
select sex,count() from text group by sex;
16、查询男生的总人数:
select sex,count() from text group by sex having sex=’男’;
17、查询每个班级共有多少人:
select class,count(*) from text group by class;
4.笔记(思维导图)

