MySQL 续集 05

2021/4/14 19:28:06

本文主要是介绍MySQL 续集 05,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

小案例1:
建表test1 test2 test3 :

DROP TABLE IF EXISTS `test1`;CREATE TABLE `test1` (
  `id` int(11) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;-- ------------------------------ Records of test1-- ----------------------------INSERT INTO `test1` VALUES ('1', '测试');INSERT INTO `test1` VALUES ('2', '测试');DROP TABLE IF EXISTS `test2`;CREATE TABLE `test2` (
  `id` int(11) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;-- ------------------------------ Records of test2-- ----------------------------INSERT INTO `test2` VALUES ('1', null);DROP TABLE IF EXISTS `test3`;CREATE TABLE `test3` (
  `id` int(11) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;-- ------------------------------ Records of test3-- ----------------------------INSERT INTO `test3` VALUES ('1', null);

执行sql 这个sql没有实际业务意义 只是为了简单使用一个case练习一下explain:

explain select d1.ct ,(select id from test3 ) id  
from (select  count(1) ct  from test1 where name ='测试') d1union     ( select name,id from test2)

结果:
在这里插入图片描述
结果说明:
按照执行顺序说:

  1. 第四行(第1个执行)
    执行 select name,id from test2
    select_type 为 union 说明第四个select是 union的第二个select

  2. 第二行 (第2个执行)
    select count(1) ct from test1 where name =‘测试’
    查询结果包含在from中 所以select_type是DERIVED

  3. 第三行(第3个执行)
    select id from test3
    select_type 为 SUBQUERY 因为他是第一个select的子查询

  4. 第一行(第4个执行)
    select d1.ct , id
    from d1

    他是union中的第一个select select_type 为PRIMARY 表示他是外层查询,table标记为 表示查询结果来自一个衍生表,derived3表示衍生来自id=3 的 select 也就是第二行

  5. 第五行(最后一个执行)
    select_type 为 UNION RESULT 他只是合并两边select的结果
    也就是<union1,4> 1表示id=1的结果 4表示id=4的结果 把两个结果进行union



这篇关于MySQL 续集 05的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程