数据库开发之内连接和外连接的详细解析

1.2 内连接

内连接查询:查询两表或多表中交集部分数据。

内连接从语法上可以分为:

  • 隐式内连接

  • 显式内连接

隐式内连接语法:

select  字段列表   from   表1 , 表2   where  条件 ... ;

显式内连接语法:

select  字段列表   from   表1  [ inner ]  join 表2  on  连接条件 ... ;

案例:查询员工的姓名及所属的部门名称

  • 隐式内连接实现

select tb_emp.name , tb_dept.name -- 分别查询两张表中的数据
from tb_emp , tb_dept -- 关联两张表
where tb_emp.dept_id = tb_dept.id; -- 消除笛卡尔积
  • 显式内连接实现

select tb_emp.name , tb_dept.name
from tb_emp inner join tb_dept
on tb_emp.dept_id = tb_dept.id;

多表查询时给表起别名:

  • tableA as 别名1 , tableB as 别名2 ;

  • tableA 别名1 , tableB 别名2 ;

使用了别名的多表查询:

select emp.name , dept.name
from tb_emp emp inner join tb_dept dept
on emp.dept_id = dept.id;

注意事项:

一旦为表起了别名,就不能再使用表名来指定对应的字段了,此时只能够使用别名来指定字段。

1.3 外连接

外连接分为两种:左外连接 和 右外连接。

左外连接语法结构:

select  字段列表   from   表1  left  [ outer ]  join 表2  on  连接条件 ... ;

左外连接相当于查询表1(左表)的所有数据,当然也包含表1和表2交集部分的数据。

右外连接语法结构:

select  字段列表   from   表1  right  [ outer ]  join 表2  on  连接条件 ... ;

右外连接相当于查询表2(右表)的所有数据,当然也包含表1和表2交集部分的数据。

案例:查询员工表中所有员工的姓名, 和对应的部门名称

-- 左外连接:以left join关键字左边的表为主表,查询主表中所有数据,以及和主表匹配的右边表中的数据
select emp.name , dept.name
from tb_emp AS emp left join tb_dept AS dept 
     on emp.dept_id = dept.id;

案例:查询部门表中所有部门的名称, 和对应的员工名称

-- 右外连接
select dept.name , emp.name
from tb_emp AS emp right join  tb_dept AS dept
     on emp.dept_id = dept.id;

注意事项:

左外连接和右外连接是可以相互替换的,只需要调整连接查询时SQL语句中表的先后顺序就可以了。而我们在日常开发使用时,更偏向于左外连接。

最近更新

  1. TCP协议是安全的吗?

    2023-12-30 22:40:04       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-30 22:40:04       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-30 22:40:04       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-30 22:40:04       18 阅读

热门阅读

  1. openssl的 openssl.cnf配置文件详解

    2023-12-30 22:40:04       24 阅读
  2. RabbitMQ消息队列安装配置及常用交换机

    2023-12-30 22:40:04       36 阅读
  3. 计算机基础--Linux详解

    2023-12-30 22:40:04       41 阅读
  4. mysql隐式转换规则

    2023-12-30 22:40:04       37 阅读