mysql左连接右连接内连接外连接区别

一道面试题,如下数据表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
 
DROP TABLE IF EXISTS `clas`;
CREATE TABLE `clas` (
  `id` tinyint(3) NOT NULL AUTO_INCREMENT,
  `classname` varchar(30) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
 
-- ----------------------------
-- Records of clas
-- ----------------------------
INSERT INTO `clas` VALUES ('1', '班级1');
INSERT INTO `clas` VALUES ('2', '班级2');
INSERT INTO `clas` VALUES ('3', '班级3');
INSERT INTO `clas` VALUES ('4', '班级4');
INSERT INTO `clas` VALUES ('5', '班级5');
INSERT INTO `clas` VALUES ('6', '班级6');
 
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL DEFAULT '',
  `cid` tinyint(3) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
 
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', '小李', '1');
INSERT INTO `user` VALUES ('2', '小张', '2');
INSERT INTO `user` VALUES ('3', '小王', '1');
INSERT INTO `user` VALUES ('4', '小赵', '3');
INSERT INTO `user` VALUES ('5', '小孙', '4');
INSERT INTO `user` VALUES ('6', '小丁', '3');
INSERT INTO `user` VALUES ('7', '小钱', '1');
INSERT INTO `user` VALUES ('8', '小周', '3');
insert into user values (9,'小黑',7);

统计每个班级的人数

1
select a.classname 班级,count(b.id) 人数 from clas a left join user b on a.id=b.cid group by b.cid;

统计大于2人的班级

1
2
select a.classname 班级,count(b.id) 人数 from clas a left join user b on a.id=b.cid group by b.cid having 人数>2;<br>
select cid 班级id,count(id) 人数 from user group by cid having 人数>2;

统计人数为0的班级

1
select a.classname 班级,count(b.id) as 人数  from clas a left join user b on a.id=b.cid group by b.cid having 人数=0;

左连接 、右连接、外连接和内连接区别

左联接依照左边的表clas(如统计每班人数的SQL语句)为基准,把满足条件的班级全部都查出来,然后根据班级到user表再统计每个班的人数,如果班级中没有人数则显示为0(如果是字符串则显示null)

1
select a.name,b.classname from user a left join clas b on a.cid=b.id;

右连接刚好和左连接相反

1
select a.name,b.classname from user a right join clas b on a.cid=b.id;

内链接 则是左右连接的交集

1
select a.name,b.classname from user a inner join clas b on a.cid=b.id;

外连接即左右连接的并集
mysql不支持full outer join 外连接 可以用 left join union right join 实现

1
select a.name,b.classname from user a left join clas b on a.cid=b.id union select a.name,b.classname from user a right join clas b on a.cid=b.id;

未经允许不得转载:开心乐窝-乐在其中 » mysql左连接右连接内连接外连接区别

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏