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字段进行排序,因此很自然地想到,如果在这两个字段上建立联合索引,利用索引本身有序的特性消除额外排序,从而提高查询性能。
    ---------------------

  • 相关阅读:
    DVWA——Brute Force(暴力破解)
    Sqli-Labs 闯关 less 54-65
    C#静态构造函数和析构函数片段化认知
    for、foreach和MoveNext循环效率粗比较
    实现一次请求加载多个js或者css
    asp.net使用httphandler打包多CSS或JS文件以加快页面加载速度
    C#向文件写、读数据
    计算机管理cmd命令行
    有二级目录的IIS配置
    WIN7 64位系统安装JDK并配置环境变量
  • 原文地址:https://www.cnblogs.com/hyhy904/p/11311211.html
Copyright © 2011-2022 走看看