MySQL - Nested-Loop Join Algorithms

MySQL 有两种join算法。Nested - Loop Join 和 Block Nested - Loop Join

Nested - Loop Join Algorithm
一种简单的嵌套循环联接(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
    }
  }
}

Block Nested - Loop Join Algorithm
使用对在外部循环中读取的行的缓冲来减少必须读取内部循环中的表的次数。 例如,如果将10行读入缓冲区并将缓冲区传递到下一个内部循环,则可以将内部循环中读取的每一行与缓冲区中的所有10行进行比较。 这将内部表必须读取的次数减少了一个数量级。
特征:

  1. 当联接的类型为ALL或索引,或范围时,可以使用联接缓冲。
  2. 连接缓冲区永远不会分配给第一个非恒定表,即使它的类型为ALL或索引也是如此。
  3. 联接中只有感兴趣的列存储在其联接缓冲区中,而不是整个行。
  4. 系统变量 join_buffer_size 确定用于处理查询的每个连接缓冲区的大小。
  5. 为每个可以缓冲的连接分配一个缓冲区,因此可以使用多个连接缓冲区来处理给定查询。
  6. 在执行连接之前分配连接缓冲区,并在查询完成后释放连接缓冲区。
# 伪代码
for each row in t1 matching range {
  for each row in t2 matching reference key {
    store used columns from t1, t2 in join buffer
    if buffer is full {
      for each row in t3 {
        for each t1, t2 combination in join buffer {
          if row satisfies join conditions, send to client
        }
      }
      empty join buffer
    }
  }
}

if buffer is not empty {
  for each row in t3 {
    for each t1, t2 combination in join buffer {
      if row satisfies join conditions, send to client
    }
  }
}
发布了213 篇原创文章 · 获赞 7 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/chuckchen1222/article/details/103462116