1.示例数据
2.内连接
3.外连接
左连接
右连接
4.全连接
5.查询左表独有的数据
6.查询右表独有的数据
7.查询左右表各自的独有的数据
创建数据库,然后用下面的sql语句创建对应的两个表
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`deptName` varchar(30) DEFAULT NULL,
`address` varchar(40) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
INSERT INTO `department` VALUES ('1', '研发部(RD)', '2层');
INSERT INTO `department` VALUES ('2', '人事部(HR)', '3层');
INSERT INTO `department` VALUES ('3', '市场部(MK)', '4层');
INSERT INTO `department` VALUES ('4', '后勤部(MIS)', '5层');
INSERT INTO `department` VALUES ('5', '财务部(FD)', '6层');
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`dep_id` int(11) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`salary` decimal(10,2) DEFAULT NULL,
`cus_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=109 DEFAULT CHARSET=utf8;
INSERT INTO `employee` VALUES ('1', '鲁班', '1', '10', '1000.00', '1');
INSERT INTO `employee` VALUES ('2', '后裔', '1', '20', '2000.00', '1');
INSERT INTO `employee` VALUES ('3', '孙尚香', '1', '20', '2500.00', '1');
INSERT INTO `employee` VALUES ('4', '凯', '4', '20', '3000.00', '1');
INSERT INTO `employee` VALUES ('5', '典韦', '4', '40', '3500.00', '2');
INSERT INTO `employee` VALUES ('6', '貂蝉', '6', '20', '5000.00', '1');
INSERT INTO `employee` VALUES ('7', '孙膑', '6', '50', '5000.00', '1');
INSERT INTO `employee` VALUES ('8', '蔡文姬', '30', '35', '4000.00', '1');
图解:
关键词:INNER JOIN ON
语句:select * from employee e INNER JOIN department d ON e.dep_id = d.id;
执行结果:
图解:
关键词:LEFT JOIN ON
语句:select * from employee e LEFT JOIN department d ON e.dep_id = d.id;
执行结果:
图解:
关键词:RIGHT JOIN ON
语句:select * from employee e RIGHT JOIN department d ON e.dep_id = d.id;
执行结果:
图解:
关键词:FULL OUTTER JOIN ON
语句:select * from employee e FULL OUTTER JOIN department d ON e.dep_id = d.id (这条语句在MySQL下无法执行)
用左右连接实现全连接:
select * from employee e LEFT JOIN department d ON e.dep_id = d.id
UNION
select * from employee e RIGHT JOIN department d ON e.dep_id = d.id;
执行结果:
图解:
关键词:LEFT JOIN ON WHERE
语句:select * from employee e LEFT JOIN department d ON e.dep_id = d.id WHERE d.id is null;
图解:
关键词:RIGHT JOIN ON WHERE
语句:select * from employee e LEFT JOIN department d ON e.dep_id = d.id WHERE e.dep_id is null;
图解:
关键词:LEFT JOIN ON WHERE
UNION
RIGHT JOIN ON WHERE
语句:SELECT * from employee e LEFT JOIN department d on e.depart_id = d.id WHERE d.id is NULL
UNION
SELECT * from employee e RIGHT JOIN department d on e.depart_id = d.id WHERE e.depart_id is NULL;
如有其它问题,欢迎大家留言,我们一起讨论,一起学习,一起进步