MYSQL之表的内连和外连
表的连接分为 内连 和 外连:
内连接
我们在多表查询中将 from 语句的多个表进行笛卡尔积
并 用where条件判断
进行多表的对接, 其实就是内连接的一种.
内连接是在开发过程中使用的最多的连接查询.
语法:
不写 inner, 默认是内连接(inner)
select 字段 from 表1 inner join 表2 on 连接条件 and 其他条件;
使用 join on 连接和之前单纯的 from where 效果是一样的, 但是这样写逻辑更清晰, 是一个递进的过程, 将连接条件和其他条件分开, 连接的条件就放在 on 中, 然后再用 where 在新表的基础上进行筛选.
案例: 显示SMITH的名字和部门名称
//方法一, 常规多表查询select ename, dept.deptno from dept, emp where dept.deptno=emp.deptno and ename='SMITH'
+-------+--------+
| ename | deptno |
+-------+--------+
| SMITH | 20 |
+-------+--------+
//方法二, join on连接表, where 筛选条件
select ename, emp.deptno from emp inner join dept on emp.deptno=dept.deptno where ename='SMITH'
+-------+--------+
| ename | deptno |
+-------+--------+
| SMITH | 20 |
+-------+--------+
外连接
外连接分为左外连接和右外连接
先提供两张表:
select * from stu;
+----+------+
| id | name |
+----+------+
| 1 | jack |
| 2 | tom |
| 3 | kity |
| 4 | nono |
+----+------+select * from exam;
+----+-------+
| id | grade |
+----+-------+
| 1 | 56 |
| 2 | 76 |
| 11 | 8 |
+----+-------+
左外连接
如果联合查询, 左侧的表完全显示我们就说是左外连接.
语法 (join 前的 inner 改为 left 即可):
select 字段名 from 表名1 left join 表名2 on 连接条件
案例一: 查询所有学生的成绩, 如果这个学生没有成绩, 也要将学生的个人信息显示出来
select stu.id, name, grade from stu left join exam on stu.id=exam.id
+----+------+--------+
| id | name | grade |
+----+------+--------+
| 1 | jack | 56 |
| 2 | tom | 76 |
| 3 | kity | <null> |
| 4 | nono | <null> |
+----+------+--------+
右外连接
和左外连接相反, 如果联合查询, 右侧的表完全显示, 我们就说是右外连接.
语法 (join 前的 inner 改为 right 即可):
select 字段 from 表名1 right join 表名2 on 连接条件;
案例:
对stu表和exam表联合查询, 把所有的成绩都显示出来, 即使这个成绩没有学生与它对应, 也要显示出来
select stu.id, name, grade from stu right join exam on stu.id=exam.id
+--------+--------+-------+
| id | name | grade |
+--------+--------+-------+
| 1 | jack | 56 |
| 2 | tom | 76 |
| <null> | <null> | 8 |
+--------+--------+-------+
列出部门名称和这些部门的员工信息, 同时列出没有员工的部门:
//法一: 左外连接
select dept.deptno, dname, empno
from dept left join emp
on dept.deptno=emp.deptno
order by dept.deptno
+--------+------------+--------+
| deptno | dname | empno |
+--------+------------+--------+
| 10 | ACCOUNTING | 7934 |
| 10 | ACCOUNTING | 7839 |
| 10 | ACCOUNTING | 7782 |
| 20 | RESEARCH | 7902 |
| 20 | RESEARCH | 7876 |
| 20 | RESEARCH | 7788 |
| 20 | RESEARCH | 7566 |
| 30 | SALES | 7900 |
| 30 | SALES | 7844 |
| 30 | SALES | 7698 |
| 30 | SALES | 7654 |
| 30 | SALES | 7521 |
| 40 | OPERATIONS | <null> |
+--------+------------+--------+//法二: 右外连接:
select d.deptno, dname, empno from emp e
right join dept d
on e.deptno=d.deptno
order by deptno
+--------+------------+--------+
| deptno | dname | empno |
+--------+------------+--------+
| 10 | ACCOUNTING | 7934 |
| 10 | ACCOUNTING | 7839 |
| 10 | ACCOUNTING | 7782 |
| 20 | RESEARCH | 7902 |
| 20 | RESEARCH | 7876 |
| 20 | RESEARCH | 7788 |
| 20 | RESEARCH | 7566 |
| 30 | SALES | 7900 |
| 30 | SALES | 7844 |
| 30 | SALES | 7698 |
| 30 | SALES | 7654 |
| 30 | SALES | 7521 |
| 40 | OPERATIONS | <null> |
+--------+------------+--------+