话不多说 直接开始

首先建立三个表用来测试


/*

SQLyog Ultimate v11.27 (32 bit)

MySQL - 5.5.55 : Database - csqltest

*********************************************************************

*/


CREATE DATABASE /*!32312 IF NOT EXISTS*/`csqltest` /*!40100 DEFAULT CHARACTER SET utf8 */;


USE `csqltest`;


/*Table structure for table `user` */


DROP TABLE IF EXISTS `user`;


CREATE TABLE `user` (

  `userId` int(10) NOT NULL AUTO_INCREMENT,

  `userName` varchar(20) DEFAULT NULL,

  `userPwd` varchar(20) DEFAULT NULL,

  PRIMARY KEY (`userId`)

) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;


/*Data for the table `user` */


insert  into `user`(`userId`,`userName`,`userPwd`) values (1,'123',NULL),(2,'阿斯顿',NULL),(3,'小明',NULL);


/*Table structure for table `usereat` */


DROP TABLE IF EXISTS `usereat`;


CREATE TABLE `usereat` (

  `uEatId` int(10) NOT NULL AUTO_INCREMENT,

  `userId` int(10) DEFAULT NULL,

  `uEatName` varchar(20) DEFAULT NULL,

  PRIMARY KEY (`uEatId`)

) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;


/*Data for the table `usereat` */


insert  into `usereat`(`uEatId`,`userId`,`uEatName`) values (1,1,'爱心'),(2,2,'靓图'),(3,3,'麦斯登'),(4,3,'阿娥'),(5,2,' 阿斯顿'),(6,2,NULL);


/*Table structure for table `userinfo` */


DROP TABLE IF EXISTS `userinfo`;


CREATE TABLE `userinfo` (

  `uInfoId` int(10) NOT NULL AUTO_INCREMENT,

  `userId` int(10) NOT NULL,

  `uInfoGd` varchar(20) DEFAULT NULL,

  PRIMARY KEY (`uInfoId`)

) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;


/*Data for the table `userinfo` */


insert  into `userinfo`(`uInfoId`,`userId`,`uInfoGd`) values (1,1,'跳舞'),(2,1,'玩游戏'),(3,3,'大带你玩');





这里我就直接拿我自己练习的表来演示了

这是三个表的意思为:

user:用户表

userInfo:兴趣爱好表

userEat:喜欢吃的东西

(每个用户可以有多个兴趣爱好和多个喜欢吃的东西)


1.内连接


关键字:inner join on

语句:select a.userId,a.userName.b.uInfoGd from user a inner join userinfo b on a.userId = b.userId;


结果:内连接


组合两个表中的记录,返回关联字段相符的记录,也就是返回两个表的有交集的部分。

内连接还有中写法,可以省略关键字


select a.userId,a.userName.b.uInfoGd from user a , userinfo b where a.userId = b.userId;

他们的效果是相同的


2.左连接

关键字:left join on


语句:SELECT a.userId,a.userName,b.uInfoGd FROM user a left join userinfo b ON a.userId = b.userId;


结果:

左连接


组合两个表,左表为主表,查询右表中和左表关联字段相符的记录,如果没有则为NULL

在这句语句里面user就是左表为主表,userinfo就是右表为附表


3.右连接

关键字:right join on


语句:SELECT a.userId,a.userName,b.uInfoGd FROM user a right join userinfo b ON a.userId = b.userId;


结果:

右连接

右连接和左连接相反,以右表为主表查找左表中相匹配的记录,和左连接相对比我们可以发现,右连接少了一条user表中的数据 因为我们是以userinfo表为主表来匹配user表中的数据


看到这里,想必对于左右表连接以及内连接 你已经有了基础的认识。(不过还是推荐自己动手练习一下。)


那现在在这里出个问题,来检验一下你的学习成果:

查出所有用户的id,名称,爱好和喜欢吃的东西


快来晃晃你的小脑袋瓜,把里面的水晃出来吧!奥利给!

下面会有答案,但还是推荐自己想哦:


.








SELECT t1.userName, t1.`userId`, t2.`uEatName`, t3.`uInfoGd`

FROM `user` t1

LEFT JOIN `usereat` t2 ON t1.`userId` = t2.`userId`

LEFT JOIN `userinfo` t3 ON t1.`userId` = t3.`userId`



在这里插入图片描述

所有你写出来了嘛?