数据库
首页 > 数据库> > Mysql中关联查询的介绍及实例

Mysql中关联查询的介绍及实例

作者:互联网

文章目录


前言

Mysql作为日常开发中常用的数据库,并且业务中的数据库查询极大情况下需要多表查询,因此掌握Mysql中的关联查询很重要。


一、建表语句

/*Table structure for table `class` */
DROP TABLE IF EXISTS `class`;
CREATE TABLE `class` (
 `id` VARCHAR(11) NOT NULL COMMENT '班级号',
 `teacherName` VARCHAR(11) NOT NULL COMMENT '班主任姓名',
 PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
/*Data for the table `class` */
INSERT  INTO `class`(`id`,`teacherName`) VALUES ('C01','李老师'),('C02','王老师'),('C03','张老师'),('C04','陈老师');
/*Table structure for table `student` */
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
 `stuId` varchar(11) NOT NULL COMMENT '学号',
 `stuName` varchar(11) NOT NULL COMMENT '学生姓名',
 `classId` varchar(11) NOT NULL COMMENT '班级号',
 PRIMARY KEY (`stuId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*Data for the table `student` */
insert  into `student`(`stuId`,`stuName`,`classId`) values ('S001','张三','C01'),('S008','李四','C03'),('S009','王五','C02'),('S110','赵六','C05');

二、交叉连接(CROSS JOIN)

SELECT * FROM student s CROSS JOIN class c
#SELECT * FROM student s,class c 和上面一种等价

三、内连接(INNER JOIN)

SELECT * FROM student s INNER JOIN class c ON s.`classId`=c.`id`
#SELECT * FROM student s,class c WHERE s.`classId`=c.`id` 和上面一种等价

四、左外连接(LEFT JOIN)

SELECT * FROM student s LEFT JOIN class c ON s.`classId`=c.`id`
SELECT * FROM student s LEFT JOIN class c ON s.`classId`=c.`id` WHERE c.`id`IS NULL

五、右外连接(RIGHT JOIN)

SELECT * FROM student s RIGHT JOIN class c ON s.`classId`=c.`id`

六、全连接(FULL JOIN)

SELECT * FROM student s LEFT JOIN class c ON s.`classId`=c.`id` 
UNION 
SELECT * FROM student s RIGHT JOIN class c ON s.`classId`=c.`id`
SELECT * FROM student s LEFT JOIN class c ON s.`classId`=c.`id` WHERE c.`id`IS NULL
UNION
SELECT * FROM student s RIGHT JOIN class c ON s.`classId`=c.`id` WHERE s.`classId` IS NULL

标签:classId,JOIN,连接,查询,实例,student,Mysql,id,class
来源: https://blog.csdn.net/weixin_44027397/article/details/113778789