在SQL执行过程中,使用太多的join回使性能下降,但由于设计和不得已的需求,不得不使用join,本篇文章将讲述join的七种方式以及其SQL的编写,通过实例来进行讲解
连接可分为三类:
select <select_list> from TableA A inner join TableB B on A.Key = B.Key
select <select_list> from TableA A left join TableB B on A.Key = B.Key
select <select_list> from TableA A right join TableB B on A.Key = B.Key
select <select_list> from TableA A left join TableB B on A.Key = B.Key where B.Key is NULL
select <select_list> from TableA A right join TableB B on A.Key = B.Key where A.Key is NULL
select <select_list> from TableA A full outer join TableB B on A.Key = B.Key
select <select_list> from TableA A full outer join TableB B on A.Key = B.Key where A.Key is NULL or B.Key is NULL
CREATE TABLE `tbl_dept` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`dept_name` VARCHAR(30) DEFAULT NULL,
`loc_add` VARCHAR(40) DEFAULT NULL,
PRIMARY KEY(`id`)
)ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT '部门表';
CREATE TABLE `tbl_emp` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(20) DEFAULT NULL,
`dept_id` INT(11) DEFAULT NULL ,
PRIMARY KEY(`id`)
)ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT '员工表';
INSERT INTO tbl_dept(dept_name,loc_add) VALUES('RD', 11);
INSERT INTO tbl_dept(dept_name,loc_add) VALUES('HR', 12);
INSERT INTO tbl_dept(dept_name,loc_add) VALUES('MK', 13);
INSERT INTO tbl_dept(dept_name,loc_add) VALUES('MIS', 14);
INSERT INTO tbl_dept(dept_name,loc_add) VALUES('FD', 15);
INSERT INTO tbl_emp(name, dept_id) VALUES('z3', 1);
INSERT INTO tbl_emp(name, dept_id) VALUES('z4', 1);
INSERT INTO tbl_emp(name, dept_id) VALUES('z5', 1);
INSERT INTO tbl_emp(name, dept_id) VALUES('w5', 2);
INSERT INTO tbl_emp(name, dept_id) VALUES('w6', 2);
INSERT INTO tbl_emp(name, dept_id) VALUES('s7', 3);
INSERT INTO tbl_emp(name, dept_id) VALUES('s8', 4);
INSERT INTO tbl_emp(name, dept_id) VALUES('s9', 51);
inner join
即可mysql> select * from tbl_emp a inner join tbl_dept b on a.dept_id = b.id;
mysql> select * from tbl_emp a left join tbl_dept b on a.dept_id = b.id;
mysql> select * from tbl_emp a right join tbl_dept b on a.dept_id = b.id;
mysql> select * from tbl_emp a left join tbl_dept b on a.dept_id = b.id where b.id is null;
mysql> select * from tbl_emp a right join tbl_dept b on a.dept_id = b.id where a.dept_id is null;
full outer join
,所以这里采用union
来合并图二和图三的结果(union
有去重效果)mysql> select * from tbl_emp a left join tbl_dept b on a.dept_id = b.id
-> union
-> select * from tbl_emp a right join tbl_dept b on a.dept_id = b.id;
union
mysql> select * from tbl_emp a left join tbl_dept b on a.dept_id = b.id where b.id is null
-> union
-> select * from tbl_emp a right join tbl_dept b on a.dept_id = b.id where a.dept_id is null;
评论