SQL statement Optimization-query different rows of the two tables NOT IN, NOT EXISTS, Join query Left Join, existsleft
In actual development, we often need to compare the differences between two or more tables and compare the data that is the same and the data is different. At this time, we can use the following three methods: 1. IN or not in, 2. EXIST or NOTEXIST, 3. use join queries (inner join, left join, or right join ).
Looking at the following data, we are going to select the depart _ information that does not exist in the pid in depart_info in user_info.
Table 1: depart_info
Table 2: user_info
Method 1: Use NOT IN
IN and not in are followed by a set, and in is a hash connection between the external table and the inner table.
SELECT d.* FROM depart_info d WHERE NOT EXISTS (SELECT * FROM user_info u WHERE d.pid = u.pid);
The test time is about seconds.
Method 2: Use NOT EXISTS
EXISTS and not exists perform loop on the External table. Each loop then queries the internal table,
SELECT d.* FROM depart_info d WHERE NOT EXISTS (SELECT * FROM user_info u WHERE d.pid = u.pid);
The test time is about seconds.
Method 3: query by connection
Connection queries include:
1. Self join (join is equivalent to inner join): the query result shows data on both sides.
2. left join: returns all data on the left, returns data on the right, and null if no data exists.
3. right join: returns all data on the right side, returns data on the left, and null if no data exists.
4. full join: returns if a table exists and the other table does not exist as nul.
SELECT d.* FROM depart_info d LEFT JOIN user_info u ON d.pid = u.pid WHERE u.pid IS NULL ;
The tested time is about S.
Summary:
1. For a small amount of data, the exists and in are similar. If there is a large amount of data (in millions of rows), we recommend that you use exists. For better data, you can use associated queries.
2. The number is small. If one of the two tables is small and the other is large, the subquery table is large with exists and the subquery table is small with in.
3. If any record returned by the subquery contains a null value,The IN query does not return any records..
4. The returned data is the data of multiple fields in two tables. We recommend that you use join queries. Not only is it fast, but the returned data can be customized.