What is a driving table
When performing multi-table join query, the definition of the driving table is:
- If the connection condition is specified, the table with fewer rows that meet the query condition is the driving table
- If the connection condition is not specified, the table with fewer rows is the driving table
Can also EXPLAIN
view SQL
may determine the execution plan statement of who is driving the table, EXPLAIN
the statement analysis out of the first row of the table that is the driving table
mysql
Why use a small table to drive the principle of a large table
mysql
The algorithm of table association Nest Loop Join
is to use the result set of the driving table as the loop basic data, and then use the data in the result set as the filter condition to query the data in the next table, and then merge the results
Example: User
table there are 10000
pieces of data, Class
table there are 20
pieces of data
-- 驱动表为 Class 表
select * from user as u left join class as c u.userid=c.userid
We need to use this User
table circulation 10000
can check out times, and if the Class
table driver User
only needs to loop table 20
times will be able to check out
The so-called small table drives a large table: that is, a small result set is used to drive a large result set
JOIN
Query how to determine the driving table and the driven table
LEFT JOIN
: The left table (master table) is the driven table, the right table (slave table) is the driven tableRIGHT JOIN
:The right table (master table) is the driven table, the left table (slave table) is the driven tableINNER JOIN
:mysql
The table with a relatively small amount of data will be selected as the driving table, and the large table as the driven table
IN
And EXISTS
using the difference
- If the amount of data query two tables rather then using
in
andexists
not very different - If one of the two tables has a smaller amount of data and the other has a larger amount of data, the larger amount of
exists
table data in the subquery is used , and the smaller amount of table data in the subquery is usedin
select * from A where id in(select id from B)
When the B
table data is set to be smaller than the A
data table is set, with IN
better EXISTS
( SQL
the efficiency): As B
the amount of data table < A
amount data table for this section SQL
, the B
table is a drive table, using mysql
a small table-driven large The principle of the table. So its execution order is: first execute the subquery, then execute the main query, use the results of the subquery to match the main query according to the conditions
select * from A where exists (select 1 from B where B.id = A.id)
When the A
table is smaller than the data set B
when the data set table, with EXISTS
better IN
( SQL
the efficiency of): it is the first execution order main query is executed, the data in the main query conditions do verification subquery