首页 > 代码库 > 七种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编写
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。