semi-join子查询优化 -- LooseScan策略

LooseScan执行semi-join子查询的一种策略。

我们将通过示例来演示这种松散(LooseScan)策略。
假设,我们正在查找拥有卫星的国家。我们可以通过以下查询获得它们(为了简单起见,我们忽略了多个国家财团拥有的卫星):

select * from Country  
where 
  Country.code in (select country_code from Satellite);

  

假设,在Satellite.country_code上有一个索引。如果我们使用该索引,我们将按卫星所属国家的顺序得到卫星:

LooseScan策略其实并不真的需要排序,真正需要的是分组。在上面的图中,卫星是根据国家分组的。例如,澳大利亚(AUS)所有的卫星在一起。这就很便于从一组中找出一个卫星,将其对应的国家进行连接,获得一个国家列表,且没有重复的国家记录:

 

上面的查询使用LooseScan之后,执行计划类似如下:

MariaDB [world]> explain select * from Country where Country.code in (select country_code from Satellite);
+----+-------------+-----------+--------+---------------+--------------+---------+------------------------------+------+-------------------------------------+
| id | select_type | table     | type   | possible_keys | key          | key_len | ref                          | rows | Extra                               |
+----+-------------+-----------+--------+---------------+--------------+---------+------------------------------+------+-------------------------------------+
|  1 | PRIMARY     | Satellite | index  | country_code  | country_code | 9       | NULL                         |  932 | Using where; Using index; LooseScan |
|  1 | PRIMARY     | Country   | eq_ref | PRIMARY       | PRIMARY      | 3       | world.Satellite.country_code |    1 | Using index condition               |
+----+-------------+-----------+--------+---------------+--------------+---------+------------------------------+------+-------------------------------------+

  

·LooseScan避免了产生重复的记录,通过将子查询表放在首位并使用其索引去从多个重复记录中选择一条记录。
因此,要想使用LooseScan,子查询应该看起来像下面的例子:

expr IN (SELECT tbl.keypart1 FROM tbl ...)

or

expr IN (SELECT tbl.keypart2 FROM tbl WHERE tbl.keypart1=const AND ...)

·LooseScan支持相关子查询
·是否开启LooseScan是由系统变量optimizer_switch中的loosescan=on|off设置的。

https://mariadb.com/kb/en/library/loosescan-strategy/

原文地址:https://www.cnblogs.com/abclife/p/10897153.html