多表查询

create table dept(
id int primary key auto_increment,
name varchar(20)
);
insert into dept values(null, '财务部'),(null, '人事部'),
(null, '销售部'),(null, '行政部')
(null, '研发部');

create table emp(
id int primary key auto_increment,
name varchar(20),
dept_id int,
foreign key(dept_id) references dept(id)
);
insert into emp values(null, '奥巴马', 1),(null, '哈利波特', 2),(null, '本拉登', 3),
(null, 'zy', 3);


一对多:在多的一方保存一的一方的主键作为外键。
一对一:在任意一方保存另一方的主键作为外键。
多对多:创建第三方关系表保存两张表的主键作为外键,保存他们的对应关系

笛卡尔积查询:将两张的记录进行相乘的操作。如果左表有n条记录,右表有m条记录,结果有n*m条结果
其中有很多错误的数据,不常用
select * from dept, emp;

内链接查询: 查询出来的是左边表和右表都能够找到对应记录的记录
select * from dept,emp where dept.id = emp.dept_id;
select * from dept inner join emp on dept.id = emp.dept_id;

外连接查询:
左外连接查询: 在内连接的基础上,增加左边表有而右边表没有的记录
select * from dept left join emp on dept.id = emp.dept_id;

右外连接查询: 在内连接的基础上,增加右边表有而左边表没有的记录
select * from dept right join emp on dept.id = emp.dept_id;

全外连接查询: 在内链接的基础上,增加左边表有而右边表没有的记录,和右边表有而左边表没有的记录
select * from dept full join emp on dept.id = emp.dept_id; //mysql 不支持全外连接
可以使用union关键字模拟全外连接
select * from dept left join emp on dept.id = emp.dept_id;
union
select * from dept right join emp on dept.id = emp.dept_id;

原文地址:https://www.cnblogs.com/superPerfect/p/4359273.html