Table of Contents
2 连接关键字" >2 连接关键字
3 连接类型" >3 连接类型
3.1 内连接" >3.1 内连接
内连接和交叉连接" >内连接和交叉连接
隐式连接" >隐式连接
3.2 外连接" >3.2 外连接
左外连接" >左外连接
右外连接" >右外连接
全外连接" >全外连接
3.3 自然连接" >3.3 自然连接
4 执行顺序" >4 执行顺序
5 连接算法" >5 连接算法
5.1 Simple Nested Loop Join(SNLJ)" >5.1 Simple Nested Loop Join(SNLJ)
5.2 Block Nested Loop Join(BNLJ)" >5.2 Block Nested Loop Join(BNLJ)
5.3 Index Nested Loop Join(INLJ)" >5.3 Index Nested Loop Join(INLJ)
Home Database Mysql Tutorial MySQL connection query super detailed explanation

MySQL connection query super detailed explanation

Jul 08, 2020 pm 05:05 PM
mysql Join query

MySQL connection query super detailed explanation

1 Function

In the database, the join operation is called a connection, and its function is to connect multiple The data of each table (through connection conditions), the data obtained from multiple tables are merged together and returned to the client as a result set. For example:

Table A:


##idnameage##1## 2B193C20Table B:
A 18


##iduid##11F22M
select A.*,B.gender from  A left join B on A.id=B.uid
Copy after login
gender
The data of the merged two tables can be obtained through connection:


id

nameagegender1A18F19 20
##2B
M3C
null

连接两个表我们可以用两个关键字:onusingon可以指定具体条件,using则指定相同名字数据类型的列作为等值判断的条件,多个则通过逗号隔开。
如下:

on: select * from A join B on A.id=B.id and B.name=''
using: select * from A join B using(id,name) = select * from A join B on 
A.id=B.id and A.name=B.name
Copy after login
  • 语法:A join | inner join | cross join B
  • 表现:A和B满足连接条件记录的交集,如果没有连接条件,则是A和B的笛卡尔积
  • 特点:在MySQL中,cross joininner joinjoin所实现的功能是一样的。因此在MySQL的官方文档中,指明了三者是等价的关系。
  • 语法:from A,B,C
  • 表现:相当于无法使用onusingjoin
  • 特点:逗号是隐式连接运算符。 隐式连接是SQL92中的标准内容,而在SQL99中显式连接才是标准,虽然很多人还在用隐私连接,但是它已经从标准中被移除。从使用的角度来说,还是推荐使用显示连接,这样可以更清楚的显示出多个表之间的连接关系和连接依赖的属性。
  • 语法:A left join B
  • 表现:左表的数据全部保留,右表满足连接条件的记录展示,不满足的条件的记录则全是null
  • 语法:A right join B
  • 表现:右表的数据全部保留,左表满足连接条件的记录展示,不满足的条件的记录则全是null

MySQL不支持全外连接,只支持左外连接和右外连接。如果要获取全连接的数据,要可以通过合并左右外连接的数据获取到,如 select * from A left join B on A.name = B.name union select * from A right join B on B.name = B.name;

这里union会自动去重,这样取到的就是全外连接的数据了。

  • 语法:A natural join B ==== A natural left join B ==== A natural right join B
  • 表现:相当于不能指定连接条件的连接,MySQL会使用左右表内相同名字和类型的字段作为连接条件。
  • 特点:自然连接也分自然内连接,左外连接,右外连接,其表现和上面提到的一致,只是连接条件由MySQL自动判定。

在连接过程中,MySQL各关键字执行的顺序如下:

from -> on|using -> where -> group by -> having -> select -> order by -> 
limit
Copy after login

可以看到,连接的条件是先于where的,也就是先连接获得结果集后,才对结果集进行where筛选,所以在使用join的时候,我们要尽可能提供连接的条件,而少用where的条件,这样才能提高查询性能。

join有三种算法,分别是Nested Loop JoinHash joinSort Merge Join。MySQL官方文档中提到,MySQL只支持Nested Loop Join这一种算法。

具体来说Nested Loop Join又分三种细分的算法:

  • SNLJ
  • BNLJ
  • INLJ

我们来看下对于连接语句select * from A left join B on A.id=B.tid,这三种算法是怎么连接的。

SNLJ是在没有使用到索引的情况下,通过两层循环全量扫描连接的两张表,得到符合条件的两条记录则输出。也就是让两张表做笛卡尔积进行扫描,是比较暴力的算法,会比较耗时。其过程如下:

for (a in A) {
     for (b in B) {
         if (a.id == b.tid) {
             output <a, b>;
         }
     }
 }
Copy after login

当然,MySQL即使在无索引可用,或者判断全表扫描可能比使用索引更快的情况下,还是不会选择使用过于粗暴的SNLJ算法,而是采用下面的算法。

INLJ是MySQL无法使用索引的时候采用的join算法。会将外层循环的行分片存入join buffer, 内层循环的每一行与整个buffer中的记录做比较,从而减少内层循环的次数,具体逻辑如下:

for (blockA in A.blocks) {
     for (b in B) {
         if (b.tid in blockA.id) {
             output <a, b>;
         }
     }
 }
Copy after login

相比于SNLJ算法,BNLJ算法通过外层循环的结果集的分块,可以有效的减少内层循环的次数。

原理

举例来说,外层循环的结果集是100行,使用SNLJ算法需要扫描内部表100次,如果使用BNLJ算法,假设每次分片的数量是10,则会先把对Outer Loop表(外部表)每次读取的10行记录放到join buffer,然后在InnerLoop表(内部表)中每次循环都直接匹配这10行数据,这样内层循环只需要10次,对内部表的扫描减少了9/10,所以BNLJ算法就能够显著减少内层循环表扫描的次数。

当然这里,不管SNLJ还是BNLJ算法,他们总的比较次数都是一样的,都是要拿外层循环的每一行与内层循环的每一行进行比较。

BNLJ算法减少的是总的扫描行数,SNLJ算法是外层循环要一行行扫描A表的数据,然后取A.id去表B一行行扫描看是否匹配。而BNLJ算法则是外层循环要一行行扫描A表的数据,然后放到内存分块里,然后去表B一行行扫描,扫描出来的B的一行数据与内存分块里的A的数据块进行比较。这里可以一次就是很多行A的数据与B的数据进行比较,而且是在内存中进行比较,速度更加快了。

影响因素

这里BNLJ算法总的扫描行数是由外层循环的数据量N,和分块数量K还有内层循环的数据量M决定的。其中分块数量K与外层循环的数据量N又是息息相关的,我们可以表示为λN,其中λ取值为(0~1)。则总扫描次数C=N+λNM

可以看出,在这个式子里,Nλ的大小都会影响扫描行数,但是λ才是影响扫描行数的关键因素,这个值越小越好(除非NM的差值非常大,这时候N才会成为关键影响因素)。

那什么会影响 λ 的大小呢?那就是 MySQL的join_buffer_size设置项的大小了。λjoin_buffer_size成倒数关系,join_buffer_size越大,分块越大,λ越小,分块数量也就越少,也就是外层循环的次数也越少。所以在使用不上索引的时候,我们要优先考虑扩大join_buffer_size的大小,这样优化效果会更明显。而在能使用上索引的时候,MySQL会使用以下算法来进行join

INLJ是MySQL判断能使用到被驱动表的索引的情况下采用的算法。假设A表的数据行为10,B表的数据行为100,且B.tid建立了索引,则对于select * from A left join B on A.id=B.tid,MySQL会采用Index Nested Loop Join。其过程如下:

for (a in A) {
     if (a.id in B.tid.Index) {
        output <a, tid.Index所在行>;
     }
 }
Copy after login

总共需要循环10次A,每次循环的时候通过索引查询一次B的数据。而如果我们反过来是B left join A的话,总共要循环100次B,由此可见如果使用join的话,需要让小表做驱动表,这样才能有效减少循环次数。但是需要注意的是,这个结论的前提是可以使用被驱动表的索引。

INLJ内层循环读取的是索引,可以减少内存循环的次数,提高join效率,但是也有缺点的,就是如果扫描的索引是非聚簇索引,并且需要访问非索引的数据,会产生一个回表读取数据的操作,这就多了一次随机的I/O操作。例如上面在索引里匹配到了tid,还要去找tid所在的行在磁盘所在的位置,具体可以见我以前的文章:MySQL索引详解之索引的存储方式。

6 Notes

  • Try to increase the connection conditions and reduce the size of the data set after join
  • Use small result set driver For large result sets, connect the tables with small filter results first, and then connect the tables with larger result sets.
  • The fields of the driven table that are join must be indexed, and use the upper index. . Using the upper index includes using this field, and there will be no index failure
  • Set a large enoughjoin_buffer_size

7 Frequently Asked Questions about Outer Joins

Q: If you want to filter the data in the driver table, for example, a left join filters the data in the left table, should you filter in the join condition or where?
A: To filter by where, the connection condition only affects the connection process and does not affect the number of results returned by the connection (in some cases, the connection condition will affect the number of results returned by the connection, such as in a left connection, When the matching data on the right is not unique)

Q: What should I do if the data rows matched by the driven table are not unique and the final connection data exceeds the data volume of the driving table? For example, for a left join, the matching data rows in the right table are not unique.
A: join Deduplicate the driven table first, for example, use group by to deduplicate: A lef join (select * from B group by name).

Related learning recommendations: mysql video tutorial

The above is the detailed content of MySQL connection query super detailed explanation. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

Monitor Redis Droplet with Redis Exporter Service Monitor Redis Droplet with Redis Exporter Service Apr 10, 2025 pm 01:36 PM

Effective monitoring of Redis databases is critical to maintaining optimal performance, identifying potential bottlenecks, and ensuring overall system reliability. Redis Exporter Service is a powerful utility designed to monitor Redis databases using Prometheus. This tutorial will guide you through the complete setup and configuration of Redis Exporter Service, ensuring you seamlessly build monitoring solutions. By studying this tutorial, you will achieve fully operational monitoring settings

How to view sql database error How to view sql database error Apr 10, 2025 pm 12:09 PM

The methods for viewing SQL database errors are: 1. View error messages directly; 2. Use SHOW ERRORS and SHOW WARNINGS commands; 3. Access the error log; 4. Use error codes to find the cause of the error; 5. Check the database connection and query syntax; 6. Use debugging tools.

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

See all articles