「这是我参与2022首次更文挑战的第10天,活动详情查看:2022首次更文挑战」。
1.4 多表查询
例题:查询出所有学生信息以及此学生的导员姓名
1.4.1 交叉连接(笛卡尔积)
笛卡尔积是指在数学中,两个集合X和Y的笛卡尓积(Cartesian product),又称直积
假设集合A={a, b},集合B={0, 1, 2},则两个集合的笛卡尔积为{(a, 0), (a, 1), (a, 2), (b, 0), (b, 1), (b, 2)}
select * from a,b
或
select * from a cross join b
1.4.2 内连接
在连接的时候使用运算符“=”号的叫等值连接
select * from a,b where a.fk = b.pk
或
select * from a [inner] join b on a.fk = b.pk
内连接又称等值连接
1.4.3 自然连接
自然连接是在两张表中寻找那些数据类型和列名都相同的字段,然后自动地将他们连接起来,并返回所有符合条件按的结果
select * from a natural join b
自然连接是内连接当中极其特殊的一种,它会自动关联两表当中字段名称和字段类型一模一样的值,也就是说两表当中字段名称和字段类型一模一样的情况下,它会自动加上 on a.fk = b.pk。
自然连接会去除重复的字段
1.4.4 外连接
1.4.4.1 左外连接
两个表在连接过程中除返回满足连接条件的行为外,还返回左表中不满足条件的行为,这种连接称为左外连接
select * from a left [outer] join b on a.pk = b.fk
1.4.4.2 右外连接
两个表在连接过程中除返回满足连接条件的行为外,还返回左表中不满足条件的行为,这种连接称为左外连接
select * from a right[outer] join b on a.pk = b.fk
1.4.4.3 全外连接
Oracle9开始新增功能,两个表在连接过程中除返回满足连接条件的行为外,还返回两个表中不满足条件的所有行为,这种连接称为全外连接.
select * from a full [outer] join b on a.pk = b.fk
1.4.5 子查询
select a.*,(select b.x from b where b.fk=a.pk) from a
1.4.6 e xists运算符
select 1 from dual where exists (select 1 from dual where 1> any(0,2,3,4))
查询有挂科的学生:
select s.* from student s where exists (select 1 from subject su where su.score < 60 and su.stu_id = s.id)