mysql的联合查询/多表查询
内连接
select *from table_1,table_2;
联合查询步骤
1.笛卡尔积
2.指定连接条件
3.指定其他条件
4.针对列进行精简/表达式运算/联合查询
实例,查询许仙个人的成绩
1)首先我们进行笛卡尔积
select*from student,score;
2)指定连接条件,进行精简结果
select*from student,score where student.id=score.student_id;
3)根据需求,补充其他条件,要求找许仙同学的成绩
select*from student,score where student.id=score.student_id and student.name='许仙';
4)针对上面的列再进行精简
select student.name ,score.score from student,score where student.id=score.student_id and student.name='许仙';
这样就进行了一个简单的联合查询.
此外针对上面情况,还有一种写法
select student.name,score.score from student join score on student.id=score.student_id and student.name='许仙';
这样也能达到这样的效果.
但是优原来的逗号改成了join关键字,并且之前表示条件的where现在要用on来表示了.
实例:查询所有同学的总成绩,以及同学的个人信息.
1)使用学生表和分数表进行笛卡尔积
select*from student,score;
2)指定连接条件
select*from student,score where student.id=score.student_id;
3)补充一些其他条件
***
4)针对列进行精简/表达式/聚合查询
select student.name ,sum(score.score) from student,score where student.id=score.student_id group by student.name;
3)查询所有同学的个人信息,课程以及对应的成绩
1)先进行笛卡尔积
select*from student,score,course;
2)指定连接条件
select*from student,score,course where student.id=score.student_id and score.course_id=course.id;
3)指定其他条件
4)针对列进行精简
select student.name,course.name,score.score from student,score,course where student.id=score.student_id and score.course_id=course.id;
当然我们也可以使用join来进行操作,以下是一个简单的实例
select student.name,course.name,score.score from student join score join course on student.id=score.student_id and score.course_id=course.id;
也可以达到一个同样的效果
另外在多表查询中,前面涉及到的去重,排序,limit也是同样涉及的.
外连接
先说一下什么是内连接,内连接就是在进行笛卡尔积的时候再给定的条件下双方都满足的情况下才展示的表,一般的,inner我们会省略不写.
先展示一下表的结构
select*from student1 inner join score1 where student1.id=score1.student_id;
对于这种情况,只展示了双方共有的,
而外连接接下来展示,
left join
select*from student1 left join score1 on student1.id=score1.student_id;
可以看到右面有NULL值,
select*from student1 right join score1 on student1.id=score1.student_id;
可以看到的是左边基本是一个NULL值.
全外连接 outer join只有oracle才行,mysql不支持.
自连接
对自己进行笛卡尔积运算
实例:显示所有计算机原理成绩比java成绩高的成绩信息
在这里计组为3,java为1
select*from score as s1,score as s2;
在这里我们要注意,要分别起别名,不然后面会出现歧义,会报错
接下来进行条件连接
select*from score as s1,score as s2 where s1.student_id=s2.student_id and s1.course_id=3 and s2.course_id=1 and s1.score>s2.score;
接下来进行列的精简
select student.name,s1.score,s2.score from student,score as s1,score as s2 where s1.student_id=s2.student_id and s1.course_id=3 and s2.course_id=1 and s1.score>s2.score and student.id=s1.student_id;
效果如上
4)查询不想毕业的同班同学
select*from student;
先拿到不想毕业同学的班级ID,再拿id来查询其他同学
select classes_id from student where student.name='不想毕业';
然后拿着班级ID来进行查询
select name from student where classes_id=1 and student.name!='不想毕业';
如此边做到了,但是还有一种复合形式可以做到
select name from student where classes_id =(select classes_id from student where name='不想毕业') and name!='不想
毕业';
效果如上,也可以做到.
联合查询
select 1union select 2
要求两个select查询的结果集,列数和类型必须进行匹配,列名不受影响,最终的列名就是select第一个列名
select *from course where name='英文' union select*from course where id<3;
效果如上所示
union还会对结果进行去重,然而union all不会去重