您好,欢迎访问一九零五行业门户网

MySQL中JOIN怎么用

简介
a的独有+ab的公有
b的独有+ab的公有
ab的公有
a的独有
b的独有
a的独有+b的独有+ab的公有
a的独有+b的独有
练习建表部门表
drop table if exists `dept`;create table `dept` ( `dept_id` int(11) not null auto_increment, `dept_name` varchar(30) default null, `dept_number` int(11) default null, primary key (`dept_id`)) engine=innodb auto_increment=1 default charset=utf8;insert into `dept` values ('1', 'aa', '100');insert into `dept` values ('2', 'bb', '200');insert into `dept` values ('3', 'cc', '300');insert into `dept` values ('4', 'dd', '400');insert into `dept` values ('5', 'hh', '500');
员工表
drop table if exists `emp`;create table `emp` ( `emp_id` int(11) not null auto_increment, `emp_name` varchar(30) default null, `emp_age` int(11) default null, `dept_id` int(11) not null, primary key (`emp_id`)) engine=innodb auto_increment=1 default charset=utf8;insert into `emp` values('1', 'zhangsan', '20', '1');insert into `emp` values('2', 'lisi', '25', '6');insert into `emp` values('3', 'wangwu', '19', '4');insert into `emp` values('4', 'zhaoliu', '29', '5');insert into `emp` values('5', 'xiaohong', '30', '2');insert into `emp` values('6', 'xiaohu', '26', '3');insert into `emp` values('7', 'zhangle', '23', '3');insert into `emp` values('8', 'qingtian', '38', '3');insert into `emp` values('9', 'xiayutian', '36', '2');insert into `emp` values('10', 'fangjia', '40', '1');
情景分析1.左连接(left join)
a的独有+ab的公有
select * from emp e left join dept d on e.dept_id=d.dept_id;
2.右连接(right join)
b的独有+ab的公有
select * from emp e right join dept d on e.dept_id=d.dept_id;
3.内连接(inner join)
ab的公有
select * from emp e inner join dept d on e.dept_id=d.dept_id;
4.左外连接(left join且右表=null)
a的独有
select * from emp e left join dept d on e.dept_id=d.dept_id where d.dept_id is null;
5. 右外连接(right join且左表=null)
b的独有
select * from emp e right join dept d on e.dept_id=d.dept_id where e.dept_id is null;
6. 全连接(full outer join)
a的独有+b的独有+ab的公有
注意:mysql不支持full outer join(在oracle支持)。
因此使用union的方式来实现,可以**合并+去重**
应用场景:
要查询的结果来自于多个表,且多个表没有直接的连接关系,但查询的信息一致时
特点:
1、要求多条查询语句的查询列数是一致的
2、要求多条查询语句的查询的每一列的类型和顺序最好一致
3、union关键字**默认去重,如果使用union all 可以包含重复项**
select * from emp e left join dept d on e.dept_id=d.dept_id union select * from emp e right join dept d on e.dept_id=d.dept_id;
7. 全外连接(full outer join且左右表=null)
a的独有+b的独有
select * from emp e left join dept d on e.dept_id=d.dept_id where d.dept_id is null union select * from emp e right join dept d on e.dept_id=d.dept_id where e.dept_id is null;
以上就是mysql中join怎么用的详细内容。
其它类似信息

推荐信息