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

  • 相关阅读:
    数组中的逆序对
    第一个只出现一次的字符
    丑数
    把数组排成最小的数
    整数中出现1的个数
    连续子数组最大和
    JS之window对象
    JS之递归(例题:猴子吃桃)
    JS中函数的基础知识
    JS数组2(冒泡排列、数组里面查找数据)
  • 原文地址:https://www.cnblogs.com/hyhy904/p/11311211.html
Copyright © 2011-2022 走看看