1.2 内连接
内连接查询:查询两表或多表中交集部分数据。
内连接从语法上可以分为:
- 隐式内连接
- 显式内连接
隐式内连接语法:
显式内连接语法:
案例:查询员工的姓名及所属的部门名称
- 隐式内连接实现
- 显式内连接实现
编辑
多表查询时给表起别名:
- tableA as 别名1 , tableB as 别名2 ;
- tableA 别名1 , tableB 别名2 ;
- 编辑
使用了别名的多表查询:
注意事项:
一旦为表起了别名,就不能再使用表名来指定对应的字段了,此时只能够使用别名来指定字段。
1.3 外连接
外连接分为两种:左外连接 和 右外连接。
左外连接语法结构:
左外连接相当于查询表1(左表)的所有数据,当然也包含表1和表2交集部分的数据。
右外连接语法结构:
右外连接相当于查询表2(右表)的所有数据,当然也包含表1和表2交集部分的数据。
案例:查询员工表中所有员工的姓名, 和对应的部门名称
编辑
案例:查询部门表中所有部门的名称, 和对应的员工名称
编辑
注意事项:
左外连接和右外连接是可以相互替换的,只需要调整连接查询时SQL语句中表的先后顺序就可以了。而我们在日常开发使用时,更偏向于左外连接。