七种join的sql编写

Posted 程序员果果

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了七种join的sql编写相关的知识,希望对你有一定的参考价值。

一、join图

 

二、sql演示

a.创建演示表及数据

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
--  Table structure for `tbl_dept`
-- ----------------------------
DROP TABLE IF EXISTS `tbl_dept`;
CREATE TABLE `tbl_dept` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `deptName` varchar(30) DEFAULT NULL,
  `locAdd` varchar(40) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

-- ----------------------------
--  Records of `tbl_dept`
-- ----------------------------
BEGIN;
INSERT INTO `tbl_dept` VALUES (\'1\', \'RD\', \'11\'), (\'2\', \'HR\', \'12\'), (\'3\', \'MK\', \'13\'), (\'5\', \'MIS\', \'14\'), (\'6\', \'FD\', \'15\');
COMMIT;

-- ----------------------------
--  Table structure for `tbl_emp`
-- ----------------------------
DROP TABLE IF EXISTS `tbl_emp`;
CREATE TABLE `tbl_emp` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `deptId` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_dept_id` (`deptId`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

-- ----------------------------
--  Records of `tbl_emp`
-- ----------------------------
BEGIN;
INSERT INTO `tbl_emp` VALUES (\'1\', \'z3\', \'1\'), (\'2\', \'z4\', \'1\'), (\'3\', \'z5\', \'1\'), (\'4\', \'w5\', \'2\'), (\'5\', \'w6\', \'2\'), (\'6\', \'s7\', \'3\'), (\'7\', \'s8\', \'4\'), (\'8\', \'s9\', \'51\');
COMMIT;

SET FOREIGN_KEY_CHECKS = 1;

b.具体sql及结果

1.图一

select * from tbl_emp a left JOIN tbl_dept b on a.deptId = b.id;

2.图二

select * from tbl_emp a INNER JOIN tbl_dept b on a.deptId = b.id;

3.图三

select * from tbl_emp a RIGHT JOIN tbl_dept b on a.deptId = b.id;

4.图四

select * from tbl_emp a left JOIN tbl_dept b on a.deptId = b.id where b.id is null;

5.图五

select * from tbl_emp a right JOIN tbl_dept b on a.deptId = b.id where a.deptid is null;

6.图六

select * from tbl_emp a RIGHT JOIN tbl_dept b on a.deptId = b.id
UNION
select * from tbl_emp a right JOIN tbl_dept b on a.deptId = b.id;

7.图七

select * from tbl_emp a LEFT JOIN tbl_dept b on a.deptId = b.id where b.id is null
UNION
select * from tbl_emp a right JOIN tbl_dept b on a.deptId = b.id where a.deptId is null;

至此结束……

 

关注我的公众号,精彩内容不能错过

 

以上是关于七种join的sql编写的主要内容,如果未能解决你的问题,请参考以下文章

Presto 中支持的七种 Join 类型

SQL Prompt7.2下载及破解教程

MySQL逻辑架构存储引擎和SQL预热 --MySQL高级篇1

spark关于join后有重复列的问题(org.apache.spark.sql.AnalysisException: Reference '*' is ambiguous)(代码片段

sql sql join片段

MySQL之SQL优化详解