9.MySQL⾼阶查询⽅法——聚合查询联合(多表)查询1. 聚合查询
⼀般需要搭配MySQL中的⼀些内置“函数”
1)count:⽤来计算结果的⾏数
<mysql>select name,decription from user;
+--------+--------------+
| name  | decription  |
+--------+--------------+
|曹操|乱世枭雄|
|刘备|仁德之主|
|孙权|年轻有为|
io编程是什么+--------+--------------+
3rows in set(0.00 sec)
<mysql>select count(*)from user;
+----------+
|count(*)|
+----------+
|3|
+----------+
1row in set(0.03 sec)
2)sum
<mysql>select*from exam_result;
+------+-----------+---------+------+---------+
索引超出范围怎么解决
| id  | name      | chinese | math | english |
+------+-----------+---------+------+---------+
|1|唐三藏|28.5|80.0|67.8|
|3|沙和尚|61.7|78.6|48.5|
|4|猪⼋戒|66.0|80.0|67.8|
|5|孙仲谋|21.0|23.0|91.5|
|6|曹孟德|67.5|75.5|67.8|
|7|刘⽞德|66.9|80.0|69.8|
+------+-----------+---------+------+---------+
6rows in set(0.00 sec)
<mysql>select sum(math)from exam_result;
+-----------+
|sum(math)|
+-----------+
|417.1|
+-----------+
1row in set(0.00 sec)
3)avg
<mysql>select avg(math)from exam_result;
+-----------+
|avg(math)|
+-----------+
mysql语句多表查询
|69.51667|
+-----------+
1row in set(0.00 sec)
4)max
<mysql>select max(math)from exam_result;
+-----------+
|max(math)|
+-----------+
|80.0|
undermine中文+-----------+
bootstrap检验stata命令
1row in set(0.03 sec)
5)min
<mysql>select min(math)from exam_result;
+-----------+
|min(math)|
+-----------+
|23.0|
+-----------+
1row in set(0.00 sec)
求⼩于80的同学的平均分
<mysql>select avg(math)from exam_result where math <80;
+-----------+
|avg(math)|
+-----------+
|59.03333|
+-----------+
1row in set(0.00 sec)
6)group by
把得到的查询结果集按照⼀定的规律分组(可以分成多个组)select[列]from[表名]group by[前⾯的列];
使⽤以上语句,就可以将这⼀列重复的类型压缩成⼀个
如果要求平均值
select[列],avg(列)from[表名]group by[前⾯的列];
如果针对group by进⾏筛选,使⽤having
select[列],avg(列)from[表名]group by[前⾯的列]having avg(列)>250;
1. 联合/多表查询
实现联合查询的基本机制:笛卡尔积
多表查询的过程就是先计算两张表的笛卡尔积,再根据⼀些条件对笛卡尔积中的记录进⾏筛选
如果针对两个⽐较⼤的表进⾏联合查询,笛卡尔积的计算开销会很⼤,最终的查效率也⽐较低,在⽣产环境中,不应该对达标进⾏联合查询。
例⼦:
已经创建了四个表结构
1)内连接
语法:
select 字段 from 表1 别名1 [inner] join 表2 别名2 on 连接条件 and 其他条件
select 字段 from 表1 别名1,表2 别名2 where 连接条件 and 其他条件;
a)查名字为“许仙”的分数
select student.id,student.name,score.student_id,score.score from student,score where student.id = score.student_id and student.name ='许仙';
把where后⾯的条件称之为:连接条件
另外⼀种写法为:
(join on ⽅式)
select student.id,student.name,score.student_id,score.score from student inner join score on student.id = score.student_id and student.name ='许仙'; b)查所有同学的总成绩以及基本信息
select student.id,student.name,sum(score.score)from student,score where student.id = score.student_id group by student.id;winform常用ui框架
b)查所有同学的每⼀科的成绩以及基本信息
select student.name, course.name, score.score from student,score,course where student.id = score.student_id and course.id = urse_id;