zl程序教程

您现在的位置是:首页 >  云平台

当前栏目

表连接

2023-09-27 14:20:56 时间

truncate t_target;  
insert into t_target  
select distinct t1.* from t_source t1,  
(select min(item_id) item_id,created_time,item_name from t_source group by created_time,item_name) t2  
where t1.item_id = t2.item_id;
        本次用时13秒,查询计划如下:

mysql> explain select distinct t1.* from t_source t1,  
    -> (select min(item_id) item_id,created_time,item_name from t_source group by created_time,item_name) t2  
    -> where t1.item_id = t2.item_id;  
+----+-------------+------------+------------+-------+---------------+-------------+---------+-----------------+--------+----------+------------------------------+
| id | select_type | table      | partitions | type  | possible_keys | key         | key_len | ref             | rows   | filtered | Extra                        |
+----+-------------+------------+------------+-------+---------------+-------------+---------+-----------------+--------+----------+------------------------------+
|  1 | PRIMARY     | t1         | NULL       | ALL   | NULL          | NULL        | NULL    | NULL            | 997281 |   100.00 | Using where; Using temporary |
|  1 | PRIMARY     | <derived2> | NULL       | ref   | <auto_key0>   | <auto_key0> | 5       | test.t1.item_id |     10 |   100.00 | Distinct                     |
|  2 | DERIVED     | t_source   | NULL       | index | idx_sort      | idx_sort    | 94      | NULL            | 997281 |   100.00 | Using index                  |
+----+-------------+------------+------------+-------+---------------+-------------+---------+-----------------+--------+----------+------------------------------+
3 rows in set, 1 warning (0.00 sec)
        和没有索引相比,子查询虽然从全表扫描变为了全索引扫描,但还是需要扫描100万行记录。因此查询性能提升并不是明显。
---------------------