数据库超话(二)
作者:互联网
多表连接查询
一、连接查询结构
1.where、inner join
-
where子句中使用的连接语句,在数据库语言中,被称为隐性连接。inner join……on子句产生的连接称为显性连接。(其他join参数也是显性连接)
-
where和inner join产生的连接关系,没有本质区别,结果也一样。
-
若两边不相等,则连接不上
2.具体内外连接
- (inner) join:内连接,理解为“有效连接”,两张表中都有的数据才会显示
- left(outer) join:(左)外链接,理解为“有左显示”,比如on
a.field=b.field,则显示a表中存在的全部数据及a、b中都有的数据,a中有、b中没有的数据以null显示 - right(outer) join:(右)外链接,理解为“有右显示”,比如on
a.field=b.field,则显示b表中存在的全部数据及a、b中都有的数据,b中有、a中没有的数据以null显示
二、内连接查询(inner)join
(1)查询刘伟老师所教授的课程号,列出教师号,教师姓名,课程号(3种方法)
① select Tno,TN,Cno
from T,TC
where T.Tno = TC.Tno and TN='刘伟'
②select Tno,TN,Cno
form T join TC on T.Tno=TC.Tno
where TN='刘伟'
③select R1.Tno,R1.TN,R2.Cno
from (select Tno,Cno from TC) as R1
inner join (select Tno,TN from T where TN = '刘伟') as R2
on R1.Tno=R2.Tno
(2)查询‘信息管理系’修了‘计算机文化基础’的学生姓名和成绩
select S.Sn,scorce
from S
join SC on S.Sno = SC.Sno
join C on C.Cno
where dept = '信息管理系' and CN ='计算机文化基础'
(3)统计每一年龄组选修课程的学生人数
select age,count(distinct sno) # 去重
from S,SC
where S.Sno = SC.Sno
group by age
三、外连接查询
(1)查询所有学生的学号,姓名,选课名称及成绩(没有选课的同学的选课信息显示为空)
select Sno,Sn,Cn,Scorce
from S
left join SC on S.Sno = SC.Sno
left join C on C.Cno=SC.Cno
(2)查询无人选课的课程名
①select CN
from C left join SC on C.Cno = SC.Cno
where SC.Cno is null # where SC.Sno is null 也可以
②select CN
from C where
Cno not in (select Cno from SC )
四、交叉查询(无特殊要求,任何表都可以交叉查询)
对学生表和课程表进行交叉查询
select * from S cross join C
五、自连接查询
(1)查询所有比“刘伟”工作高的教师姓名、工资、和刘伟的工资(3种)
①select X.TN,X.Sal as Sal_a,Y.Sal as Sal_b
from T as X ,T as Y
where X.sal >Y.sal and Y.TN = '刘伟'
②select X.TN,X.Sal,Y.Sal
from T as X inner join T as Y
on X.Sal >Y.Sal and Y.TN = ’刘伟
③select R1.TN,R1.Sal,R2.Sal
from (select TN,Sal from T) as R1
inner join
(select Sal from T where TN =‘刘伟') as R2
on R1.Sal <font color = 'red'> > R2.Sal #大于连接
(2)检索所有学生姓名,年龄和选课名称(2种)
①select SN,Age,CN
from S,SC ,C
where S.Sno = SC.Sno and SC.Cno = C,.Cno
②select
from
(select Sno,SN,Age from S) as R3 #从S表把学号,姓名,年龄选出来,放入R3
inner join
(select R2.Sno,R1.CN #从C,SC查出学课学生的学号,被选的课程名,放到R4
from
(select Cno,Cn from C ) as R1
inner join
(select Sno,Cno from SC) as R2
on R1.Cno = R2.Co) as R4
on R3.Sno = R4.Sno #R3,R4连接,检索所有学生姓名,年龄和选课名称
标签:join,Sal,Sno,数据库,超话,SC,Cno,select 来源: https://blog.csdn.net/qq_30336973/article/details/111415756