mysql内连接
文章目录多表连接一、内连接初识(内连接两张表)二、内连接多张表三、为表起别名题型综合多表连接多表连接的基础,要连接的表必须具有相同意义的字段(有关系的表);多表连接什么时候用:顾名思义,肯定是所查询的问题的涉及到不止一个表;一、内连接初识(内连接两张表)内连接:(1)等值连接(实用性强)(2)不等值连接内连接语法结构:select 查询字段 from表1[inner] join 表2 on表1.关
多表连接
多表连接的基础,要连接的表必须具有相同意义的字段(有关系的表);
多表连接什么时候用:顾名思义,肯定是所查询的问题的涉及到不止一个表;
一、内连接初识(内连接两张表)
内连接:
(1)等值连接(实用性强)
(2)不等值连接
内连接语法结构:
select 查询字段 from表1[inner] join 表2 on表1.关系字段=表2.关系字段;(等值连接)
(1)内连接特点:满足连接条件的才会出现在结果里面;
(2)内连接是左右拼接表;
注:连接条件中如果使用‘=’,则叫做等值连接
例1:内连接a表和b表,查询所有字段;
内连接特点:符合条件的记录才会出现在查询结果中;(内连接相当于左右拼接表)union(上下拼接表)
例2:student表和sc表内连接(等值连接),查询所有(sno,sname,sdept,cno,degree)字段
注意点:
(1)内连接的表必须是要有关系的表(即具有相同意义字段的表)
(2)当查询的字段同时出现在连接的表当中,必须明确说明是那个表里的字段,不然会出现错误;
其中内连接可以写成上面的形式:
连接条件写在from子句中:
select 查询字段 from 表1[inner] join 表2 on 表1.关系字段=表2.关系字段;
也可以写成如下的形式,连接条件写在where子句中
select 查询字段 from 表1,表2 where 表1.关系字段=表2.关系字段;
二、内连接多张表
例3:将student表和sc表以及course表内连接,查询所有字段;
select * from student a,sc b,course c where a.sno=b.sno and b.cno=c.cno;
例4:将student表和sc表以及course表内连接,查询sno,sname,sdept,cno,cname字段;
select a.sno,sname,sdept,b.cno,cname from
student a,sc b,course c
where a.sno=b.sno and b.cno=c.cno;
(给每个表进行一次命名,便于选择)
From A [inner] join B on A.sno=B.sno[inner] join C on B.cno=C.cno
以此类推到多张表………
三、为表起别名
Select字段名 from表名[as] 别名;
修改上面的例题
1、将student表和sc表以及course表内连接,查询sno,sname,sdept,cno,cname字段;(给表起别名)
2、内连接teaching,teacher,sc,student表查询所有字段;
与题型有关表的标签如下:
student(学号、姓名、性别、课程、系别、课程号等)
teacher(工号、姓名、性别、系别等)
teaching(课程号 工号)
course(课程号 课程名字)
sc(学号、课程号、成绩)
题型综合
1、内连接course表和sc表,查询所有字段;(等值连接)
select * from course a,sc b where a.cno=b.cno;
2、内连接course和sc表,查询cno,cname,sno,degree字段;
select cno,cname,sno,degree from course a,sc b where a.cno=b.cno;
3、内连接teacher,teaching,sc查询tno,tname,cno,sno字段;
select tno,tname,cno,sno from teacher a,teaching b,sc c
where a.tno=b.tno and b.cno=c.cno;
4、内连接teaching,teacher,sc,student表查询tno,tname,cno,sno,sname,sdept字段
select tno,tname,cno,sno,sname,sdept from teaching a,teacher b,sc c,student d
where a.tno=b.tno and a.cno=c.cno and c.sno=d.sno;
5、内连接teaching,teacher,sc,student,course表,查询sname,sno,cno,cname,
select sname,sno,cno,cname from teaching a,teacher b,sc c,student d,course e
where a.tno=b.tno and a.cno=c.cno and c.sno=d.sno and c.cno=e.cno;
思考题:
(1)查询电子工程系选修课程学生的学号,名字,选修的课程以及对应的成绩;
(2)输出已经选修课程的女生的学号、姓名、课程号、成绩;
更多推荐
所有评论(0)