zoukankan      html  css  js  c++  java
  • 使用变量

    set @a:='1000-01-01 00:00:00';  
    set @b:=' ';  
    set @f:=0;  
    truncate t_target;  
    insert into t_target  
    select item_id,created_time,modified_time,item_name,other  
      from   
    (select t0.*,if(@a=created_time and @b=item_name,@f:=0,@f:=1) f, @a:=created_time,@b:=item_name  
      from   
    (select * from t_source order by created_time,item_name) t0) t1 where f=1;
            这种方法用时13秒,查询计划如下:

    mysql> explain select item_id,created_time,modified_time,item_name,other  
        ->   from   
        -> (select t0.*,if(@a=created_time and @b=item_name,@f:=0,@f:=1) f, @a:=created_time,@b:=item_name  
        ->   from   
        -> (select * from t_source order by created_time,item_name) t0) t1 where f=1; 
    +----+-------------+------------+------------+------+---------------+-------------+---------+-------+--------+----------+----------------+
    | id | select_type | table      | partitions | type | possible_keys | key         | key_len | ref   | rows   | filtered | Extra          |
    +----+-------------+------------+------------+------+---------------+-------------+---------+-------+--------+----------+----------------+
    |  1 | PRIMARY     | <derived2> | NULL       | ref  | <auto_key0>   | <auto_key0> | 4       | const |     10 |   100.00 | NULL           |
    |  2 | DERIVED     | <derived3> | NULL       | ALL  | NULL          | NULL        | NULL    | NULL  | 997282 |   100.00 | NULL           |
    |  3 | DERIVED     | t_source   | NULL       | ALL  | NULL          | NULL        | NULL    | NULL  | 997282 |   100.00 | Using filesort |
    +----+-------------+------------+------------+------+---------------+-------------+---------+-------+--------+----------+----------------+
    3 rows in set, 5 warnings (0.00 sec)
    最内层的查询扫描t_source表的100万行,并使用文件排序,生成导出表derived3。
    第二层查询要扫描derived3的100万行,生成导出表derived2,完成变量的比较和赋值,并自动创建一个导出列f上的索引auto_key0。
    最外层使用auto_key0索引扫描derived2得到去重的结果行。
            与上面方法2比较,总的扫描行数不变,都是200万行。只存在一点微小的差别,这次自动生成的索引是在常量列 f 上,而表关联自动生成的索引是在item_id列上,所以查询时间几乎相同。

            至此,我们还没有在源表上创建任何索引。无论使用哪种写法,要查重都需要对created_time和item_name字段进行排序,因此很自然地想到,如果在这两个字段上建立联合索引,利用索引本身有序的特性消除额外排序,从而提高查询性能。
    ---------------------

  • 相关阅读:
    Tomcat 7.x 6.x 和 JDK 7 旧版本下载教程
    下载ios系统文件,使用UltraISO刻录系统(windows Server)光盘,安装操作系统
    MSDN, 我告诉你
    669. 修剪二叉搜索树
    99. 恢复二叉搜索树
    windows系统 python安装uwsgi教程
    mysql5.7修改密码命令
    客户端浏览器访问django服务器
    二、kafka的环境部署+命令行
    二十、SpringCloud Alibaba Seata处理分布式事务(一、基础)
  • 原文地址:https://www.cnblogs.com/hyhy904/p/11311211.html
Copyright © 2011-2022 走看看