时间:2022-09-13 08:49:20 | 栏目:Mysql | 点击:次
建表
部门表
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;