Mysql 在不同版本对join的实现有不同的实现方式,mysql5.7之前,是通过Nested Loop join方式实现的,在mysql 8以后对这种嵌入循环查询的方式采用hash join的算法进行了优化。
注:如下引用内容均摘抄与Mysql官网
Nested Loop Join
MySQL executes joins between tables using a nested-loop algorithm or variations on it.
MySQL使用嵌套循环算法或它的变体来执行表之间的连接。
有如下两种算法:
-
Nested-Loop Join Algorithm
A simple nested-loop join (NLJ) algorithm reads rows from the first table in a loop one at a time, passing each row to a nested loop that processes the next table in the join. This process is repeated as many times as there remain tables to be joined.
一个简单的嵌套循环联接(NLJ)算法一次从循环中的第一个表读取一行,将每一行传递到一个嵌套循环,该循环处理联接中的下一个表。只要还有需要连接的表,这个过程就会重复多次。如果使用简单的NLJ算法,连接处理如下:
for each row in t1 matching range { for each row in t2 matching reference key { for each row in t3 { if row satisfies join conditions, send to client } } }
因为NLJ算法一次只将一行从外部循环传递到内部循环,所以它通常读取在内部循环中处理的表多次。
分析 t1 join t2 :