search
HomeDatabaseMysql TutorialDetailed explanation of database hash connection (new feature of MySQL)

Detailed explanation of database hash connection (new feature of MySQL)

Overview

For a long time, the only algorithm MySQL used to perform joins was the nested loop algorithm. algorithm), but the nested loop algorithm is very inefficient in certain scenarios, which is also a problem that MySQL has been criticized for.

With the release of MySQL 8.0.18, MySQL Server can use hash join. This article will briefly introduce how to implement hash join and see how it works in MySQL. , when to use it, and what are the restrictions.

Recommended study: MySQL tutorial

Introduction to hash connection

What is a hash connection?

Hash join is a join algorithm used in relational databases and can only be used for joins with equal join conditions (on a.b = c.b). It is generally more efficient than the nested loop algorithm (except when the probe end is very, very small), especially if no index is hit.

To put it simply, the hash connection algorithm is to first load a small table into the memory hash table, then traverse the data of the large table, match the qualified data in the hash table row by row, and return it to the customer end.

Detailed explanation of database hash connection (new feature of MySQL)

(The hash table is just an example, for understanding, the key of the actual hash is the value of the connection, and the value is the data row linked list)

Usually the hash The connection is divided into two phases, the build phase and the probe phase. In the construction phase, the appropriate table is first selected as the "build input", the hash table is built, and then the records of another "detection input" table are traversed in order to detect the hash table to find records that meet the connection conditions.

The above picture is an example to query the province corresponding to the city. We assume that city is the construction input. During the construction phase, the server builds a city hash table, traverses the city table, and puts the rows into the hash table in sequence. The key is hash(province_id) and the value is the corresponding city row. `

During the probe phase, the server starts reading lines from the probe input (province). For each row the hash table is probed for matching rows using the hash(province.province_id) value as the lookup key.

That is, when the construction input can all be loaded into memory, each detection line is scanned only once, and a matching line between the two inputs can be found using a constant-time search.

What should I do if there is too much data that cannot be put into the memory?

Loading all the build input into memory is undoubtedly the most efficient, but in some cases, the memory is not enough to load the entire table into memory, so it needs to be processed in batches.

There are two common methods:

Loading into memory for processing in batches

1. Reading the maximum memory can Create a hash table to accommodate the records, construct the input, and generate a hash table;

2. Traverse the detection input to conduct a full detection of this part of the hash table;

3. Clean up the hash table and restart Continue this process until all processing is complete.

This method will cause the entire detection input table to be scanned multiple times.

Write to File Processing

1. When the memory runs out during the build hash table phase, the server will write the remaining build input to many disks In small files, all small file blocks can be read into the memory after calculation and a hash table is created (to avoid that the file blocks are too large and cannot be loaded into the memory later and need to be separated again);

2. In the detection phase, due to The detection line may match a line of the build input written to disk, so the detection input also needs to be written to disk;

3. After the detection phase is completed, the block file is read from disk and loaded into memory In the hash table, read the corresponding block file from the detection input and detect the matching item;

4. After processing, move to the next pair of block files until all processing is completed.

Hash join implementation in MySQL

MySQL will select the smaller of the two inputs as the build input (calculated in bytes), and when there is enough memory In some cases, the build input is loaded into memory for processing, and in cases where it is not enough, it is processed by writing to a file.

You can use the join_buffer_size system variable to control the memory usage of hash connections. The memory used by hash connections cannot exceed this amount. When this amount is exceeded, MySQL will use files for processing.

If memory exceeds join_buffer_size and files exceed open_files_limit, execution may fail.

You can use the following two solutions:

● Increase join_buffer_size to avoid hash connection overflow to disk

● Increase open_files_limit

Under what circumstances will MySQL use hash joins?

In MySQL version 8.0.18, if tables are joined together using one or more equal join conditions, and there are no indexes available for the join conditions, a hash join will be used. MySQL prefers to use index lookups to support nested loops if an index is available.

By default, MySQL will use hash joins whenever possible, which can be enabled or disabled in the following two ways:

● Set global or session variables (hash_join = on or hash_join = off);

SET optimizer_switch="hash_join=off";

● Use hints (HASH_JOIN or NO_HASH_JOIN).

We will use the following query as an example:

EXPLAIN FORMAT = tree
SELECT
  city.name AS city_name,
  province.name AS province_name
FROM
  city
  JOIN province
    ON city.province_id = province.province_id;

The output is:

| -> Inner hash join (city.province_id = province.province_id)  (cost=1333.82 rows=1329)
    -> Table scan on city  (cost=0.14 rows=391)
    -> Hash
        -> Table scan on province  (cost=3.65 rows=34)

Hash joins can also be used in multiple join queries, as long as there is an equal value join , you can use hash connection.

For example, the following query:

EXPLAIN FORMAT= TREE
SELECT
  city.name AS city_name,
  province.name AS province_name,
  country.name AS country_name
FROM
  city
  JOIN province
    ON city.province_id = province.province_id
    AND city.id < 50
  JOIN country
    ON province.province_id = country.id

The output is:

| -> Inner hash join (city.province_id = country.id)  (cost=23.27 rows=2)
    -> Filter: (city.id < 50)  (cost=5.32 rows=5)
        -> Index range scan on city using PRIMARY  (cost=5.32 rows=49)
    -> Hash
        -> Inner hash join (province.province_id = country.id)  (cost=4.00 rows=3)
            -> Table scan on province  (cost=0.59 rows=34)
            -> Hash
                -> Table scan on country  (cost=0.35 rows=1)

Hash connection is also applicable to "Cartesian product", that is, no query conditions are specified, as follows:

EXPLAIN FORMAT= TREE
SELECT
  *
FROM
  city
  JOIN province;

The output is:

| -> Inner hash join  (cost=1333.82 rows=13294)
    -> Table scan on city  (cost=1.17 rows=391)
    -> Hash
        -> Table scan on province  (cost=3.65 rows=34)

Under what circumstances will MySQL not use hash joins?

1. Currently, MySQL hash join only supports inner joins. Anti-joins, semi-joins and outer joins are still executed using block nested loops.

2. If the index is available, MySQL will prefer to use index lookup to support nested loops;

3. When there is no equivalent query, nested loops will be used.

is as follows:

EXPLAIN FORMAT=TREE
SELECT
  *
FROM
  city
  JOIN province
    ON city.province_id < province.province_id;

The output is:

| <not executable by iterator executor>

How to check whether statement execution uses hash connection?

EXPLAIN FORMAT= TREE can be used in MySQL 8.0.16 and later versions. TREE provides tree-like output and describes query processing more accurately than the traditional format. It is the only display format. The format of the Greek connection usage.

In addition, you can also use EXPLAIN ANALYZE to view hash connection information.


The above is based on MySQL community Server 8.0.18.

The above is the detailed content of Detailed explanation of database hash connection (new feature of MySQL). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:oschina. If there is any infringement, please contact admin@php.cn delete
图文详解mysql架构原理图文详解mysql架构原理May 17, 2022 pm 05:54 PM

本篇文章给大家带来了关于mysql的相关知识,其中主要介绍了关于架构原理的相关内容,MySQL Server架构自顶向下大致可以分网络连接层、服务层、存储引擎层和系统文件层,下面一起来看一下,希望对大家有帮助。

mysql怎么替换换行符mysql怎么替换换行符Apr 18, 2022 pm 03:14 PM

在mysql中,可以利用char()和REPLACE()函数来替换换行符;REPLACE()函数可以用新字符串替换列中的换行符,而换行符可使用“char(13)”来表示,语法为“replace(字段名,char(13),'新字符串') ”。

mysql的msi与zip版本有什么区别mysql的msi与zip版本有什么区别May 16, 2022 pm 04:33 PM

mysql的msi与zip版本的区别:1、zip包含的安装程序是一种主动安装,而msi包含的是被installer所用的安装文件以提交请求的方式安装;2、zip是一种数据压缩和文档存储的文件格式,msi是微软格式的安装包。

mysql怎么去掉第一个字符mysql怎么去掉第一个字符May 19, 2022 am 10:21 AM

方法:1、利用right函数,语法为“update 表名 set 指定字段 = right(指定字段, length(指定字段)-1)...”;2、利用substring函数,语法为“select substring(指定字段,2)..”。

mysql怎么将varchar转换为int类型mysql怎么将varchar转换为int类型May 12, 2022 pm 04:51 PM

转换方法:1、利用cast函数,语法“select * from 表名 order by cast(字段名 as SIGNED)”;2、利用“select * from 表名 order by CONVERT(字段名,SIGNED)”语句。

MySQL复制技术之异步复制和半同步复制MySQL复制技术之异步复制和半同步复制Apr 25, 2022 pm 07:21 PM

本篇文章给大家带来了关于mysql的相关知识,其中主要介绍了关于MySQL复制技术的相关问题,包括了异步复制、半同步复制等等内容,下面一起来看一下,希望对大家有帮助。

带你把MySQL索引吃透了带你把MySQL索引吃透了Apr 22, 2022 am 11:48 AM

本篇文章给大家带来了关于mysql的相关知识,其中主要介绍了mysql高级篇的一些问题,包括了索引是什么、索引底层实现等等问题,下面一起来看一下,希望对大家有帮助。

mysql怎么判断是否是数字类型mysql怎么判断是否是数字类型May 16, 2022 am 10:09 AM

在mysql中,可以利用REGEXP运算符判断数据是否是数字类型,语法为“String REGEXP '[^0-9.]'”;该运算符是正则表达式的缩写,若数据字符中含有数字时,返回的结果是true,反之返回的结果是false。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment