Mysql左连接left join on与右连接 right join on,内连接union区别

本文详细介绍了SQL中的左连接、右连接及内连接等查询方式,并通过具体实例进行演示,包括如何使用union关键字来合并多个查询结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数据库中建立了两张表:
tb_stu表:

DROP TABLE IF EXISTS `tb_stu`;
CREATE TABLE `tb_stu` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(15) DEFAULT NULL,
  `sex` varchar(5) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tb_stu
-- ----------------------------
INSERT INTO `tb_stu` VALUES ('1', 'a', '男');
INSERT INTO `tb_stu` VALUES ('2', 'b', '女');
INSERT INTO `tb_stu` VALUES ('3', 'c', '男');
INSERT INTO `tb_stu` VALUES ('4', 'd', '男');
INSERT INTO `tb_stu` VALUES ('5', 'e', '女');

tb_school表:

DROP TABLE IF EXISTS `tb_school`;
CREATE TABLE `tb_school` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(15) DEFAULT NULL,
  `school` varchar(15) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tb_school
-- ----------------------------
INSERT INTO `tb_school` VALUES ('1', '1', '1');
INSERT INTO `tb_school` VALUES ('2', '2', '2');
INSERT INTO `tb_school` VALUES ('3', '3', '3');
INSERT INTO `tb_school` VALUES ('4', '4', '4');
INSERT INTO `tb_school` VALUES ('5', '5', '5');
INSERT INTO `tb_school` VALUES ('6', 'a', 'a');
INSERT INTO `tb_school` VALUES ('7', 'b', 'b');
INSERT INTO `tb_school` VALUES ('8', 'c', 'c');
INSERT INTO `tb_school` VALUES ('9', 'd', 'd');
INSERT INTO `tb_school` VALUES ('10', 'e', 'e');

表的结构如下:
这里写图片描述
或者这样查看
这里写图片描述
查看表的结构命令是:

explain tb_school(表名);
或者
show colunms from tb_stu(表名);
或者
mysql> use information_schema
Database changed
mysql> select * from columns where table_name='tb_stu';

表tb_stu有五条数据,表tb_school有十条数据。
其中tb_stu 和 tb_school 相同的字段有五条相同是数据。
现在通过左连接查询:

SELECT
    a.id, a.name,a.sex,
    b.id as b_id,
    b.name as b_name,
b.school
FROM
    tb_stu a
LEFT JOIN tb_school b ON a.name = b.name

这里写图片描述
从图中看到通过左连接查询结果有五条数据。
总结:左连接查询是以左表为基表,其中 on 是条件。有两张表或者多张表中有相同的字段才会查询出来。

Mysql 有连接:

SELECT
    a.id, a.name,a.sex,
    b.id as b_id,
    b.name as b_name,
b.school
FROM
    tb_stu a
RIGHT JOIN tb_school b ON a.name = b.name

这里写图片描述
总结:从查询结果可以看到,右连接是以右边为基表,on 的条件不管有没有,都会以右连接的表为基表,故此,查询结果是10条记录。

内连接:

SELECT
    a.id, a.name,a.sex,
    b.id as b_id,
    b.name as b_name,
b.school
FROM
    tb_stu a
INNER  JOIN tb_school b ON a.name = b.name

这里写图片描述
总结:内连接是将表中相同的条件查询出来

union关键字用法:

SELECT
    a.id,
    a.name,
    a.sex
FROM
    tb_stu a
    GROUP BY
    a.name
UNION
    SELECT
        b.id AS b_id,
        b.name AS b_name,
        b.school
    FROM
        tb_school b
GROUP BY
b.name

这里写图片描述
从内连接查询结果可以看到:查询总记录数是15。
总结:内连接是将两张表中所有的结果都查询出来。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值