前置条件;a表和b表
笛卡尔积查询:select * from a,b;
--查出来的结果条数是(a表行数* b表行数)
--a表的每条记录和b表每条记录 组合
--缺点:有很多错误数据,必须过滤出正确的
内连接
作用:查询两边的公共部分
方式一:select * from a,b where a..关联字段 = b.关联字段;
方式二:select * from a inner join b on a.关联字段 =b.关联字段;
左连接
作用:左表全部显示,依据左表的显示右边没查到的显示为null;
select * from a left join b on a.关联字段 = b.关联字段。 a是左表
右连接
作用:右表全部显示,依据右表的显示左表没有查到的显示为null;
select * from a right join b on a.关联字段 = b.关联字段。 b是右表
多表查询
子查询
--select max(price) from b;
select id from b where price=3.5;
select name from a where id= 2;
--select name from a where id in
(select id from b where price=
(select max(price) from b))
in的用法
in 表示条件应该是在多个列值中。
in:使用在where后面,经常表示是一个列表中的数据,只要被查询的数据在这个列表中存在即可。
-- 需求:查询不及格的学生(使用in完成)。
--select * from student where id in
(select student_id from studentcourse where score<60);
all的用法
注意:all使用 只能用于子查询 直接给出数字是不可以的(语法错误)
需求:查询年龄最大的学生的信息。
--select * from student where age=(
select max(age) from student
);
--select * from student where age >= all(
select age from student
);
any和some
需求:查询成绩是90的学生的信息
--select * from student where id in (
select student_id from studentcourse where score=90
);
--select * from student where id=any(
select student_id from studentcourse where score=90
);
--select * from student where id=some(
select student_id from studentcourse where score=90
);
as的用法
as:不仅可以用来做列的别名,还可以将查询结果通过as作为一张表来使用。
as 做一个别名 ,我们可以用过 别名.属性 表名.属性 将你的查询结果作为中间表查询
需求:查询不及格的学生信息和不及格分数
--select student.*,temp.score from student,
(select student_id,score from studentcourse where score<60)
as temp where student.id=temp.student_id;
limit的用法
作用:限制查询结果返回数量;即查询数据库中的一部分数据
mysql中limit的用法:返回前几条或者中间某几行数据
-select * from 表名 limit offset,row_count;
--select * from 表名 limit 1,4;
--1表示索引,这里索引从0开始。
--4表示查询记录数。
上述就表示从第2条记录开始查询,一共查询4条,即到第5条。
强化练习
-- 1、查询每个平均成绩大于70分的同学的学号和平均成绩。
select student_id,avg(score) from studentcourse group by student_id having avg(score)>70;
-- 2、查询每个同学的学号、姓名、选课数、总成绩。
思路
select student_id,sum(score) from studentcourse group by student_id having sum(score)
select student_id,count(course_id) from studentcourse group by student_id having count(course_id)
select student_id,course_id from studentcourse group by student_id,course_id
答案
select student.*,temp.cou,temp.sumscore from student,
(select student_id,count(*)as cou,sum(score)as sumscore from studentcourse group by student_id)
as temp where student.id=temp.student_id
注意:student_id,sum(score) ,count(course_id)这三个字段放在一起报错,重点count(*)
-- 3、查询学过赵云老师所教课的同学的学号、姓名。
select student.id,student.name from student,
(select student_id from studentcourse where course_id in (
select id from course where teacher_id =(
select id from teacher where name='赵云'
)))as temp where temp.student_id=student.id
聚合函数定义:多个数据进行运算,运算出一个结果count函数 (统计行数)--select count(*) from 表名; 统计表中的行数--select count(列名) from 表名; 按具体列统计行数,不统计null值所在行sum函数(求和)--select sum(列名),sum(列名),... from 表名; 使用sum进行多列求和的时候, nul...