码迷,mamicode.com
首页 > 数据库 > 详细

七种join的sql编写

时间:2017-08-01 19:23:33      阅读:342      评论:0      收藏:0      [点我收藏+]

标签:comm   create   idt   nod   编写   数据   set   arch   ble   

一、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编写

标签:comm   create   idt   nod   编写   数据   set   arch   ble   

原文地址:http://www.cnblogs.com/huanchupkblog/p/7269246.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!