借助 DBMS 中的示例解释连接操作
dbmsdatabasebig data analytics更新于 2026/1/13 3:07:17
连接操作根据一个条件将两个关系组合起来,用⋈表示。连接有多种类型,包括 Theta 连接、自然连接、外连接(左外连接、右外连接、全外连接)。
示例
考虑以下示例 −
步骤 1
查询
create a table student (name char(30), regno number(10));
输出
Table created.
步骤 2
查询
insert into student values (‘hari’, 1); Insert into student values (‘subbu’, 2); Insert into student values (‘srinu’, 3);
输出
3 rows created.
步骤 3
查询
select * from student;
输出
| Name | Regno |
|---|---|
| Hari | 1 |
| Subbu | 2 |
| Srinu | 3 |
步骤 4
查询
Create table marks(regno number(10), total number(10));
输出
table created.
步骤 5
查询
insert into marks values (1, 400); Insert into marks values(2,450); Insert into marks values (3, 300);
输出
3 rows created.
步骤 6
查询
select * from marks;
输出
| Regno | Total |
|---|---|
| 1 | 400 |
| 2 | 450 |
| 3 | 300 |
自然连接 − 如果我们在相等的条件下连接两个表,则称为自然连接或等值连接。通常,连接被称为自然连接。
自然连接的语法如下 −
select columnname(s) from tablename1 join tablename2 on tablename1.columnname=tablename2.columnname;
步骤 7
查询
Select * from student join marks on student.regno = marks.regno;
输出
| Name | Regno | Regno | Total |
|---|---|---|---|
| Hari | 1 | 1 | 400 |
| Subbu | 2 | 2 | 450 |
左连接 − 它是自然连接的扩展,用于处理关系的缺失值。
步骤 8
查询
Select * from student left join marks on student.regno = marks.regno;
输出
| Name | Regno | Regno | Total |
|---|---|---|---|
| Hari | 1 | 1 | 400 |
| Subbu | 2 | 2 | 450 |
| Srinu | 3 | NULL | NULL |
Right join − Here all the tuples of table2 (right table) appear in the output.
table1 中不匹配的值用 NULL 填充
步骤 9
查询
Select * from student right join marks on student.regno = marks.regno;
输出
| Name | Regno | Regno | Total |
|---|---|---|---|
| Hari | 1 | 1 | 400 |
| Subbu | 2 | 2 | 450 |
| NULL | NULL | NULL | NULL |
全连接 − 全外连接=左外连接 U 右外连接
步骤 10
查询
Select * from student full join on student.regno = marks.regno;
输出
| Name | Regno | Regno | Total |
|---|---|---|---|
| Hari | 1 | 1 | 400 |
| Subbu | 2 | 2 | 450 |
| Srinu | 3 | NULL | NULL |
| NULL | NULL | 5 | 350 |

