首页 > 代码库 > 七种join的sql编写

七种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编写