MySQL query for data that exists in one table but not in another

Two tables, A and B, find out that in the id field, there is table A, but there is no data in table B.

Example: a table b table

                           

 

Method 1:  Use not in, easy to understand, low efficiency ~Execution time: 1.395 seconds~

SELECT DISTINCT a.id FROM  a WHERE a.ID NOT IN (SELECT id FROM b)

Method 2:  Use left join...on... , "B.ID isnull" indicates the records whose B.ID field is null after left join ~Execution time: 0.739 seconds~

select A.ID from A left join B on A.ID=B.ID where B.ID is null

Method 3: The logic is relatively complex, but the speed is the fastest ~Execution time: 0.570 seconds~

SELECT * FROM  a 
WHERE (SELECT COUNT(1) FROM b WHERE A.ID = B.ID) = 0;

I have not tested the efficiency, this is the test result of the predecessors, and the last method of the original blog is wrong .

The third approach is explained below:

In order to  first SELECT * FROM a, if there is no where, then query all.

Now that there is where, the scope is narrowed down. You can understand it this way. It traverses its own values ​​in order, and the current value is only taken out when the expression after where is equal to true. (''' is only for ease of understanding, the reality may not be like this').

Then look at the sub-query, the sub-query count(1) only increases the value of count by one when the following condition a.id=b.id  . There is no duplicate data in this table, that is, when a.id=b.id, count(1)=1.

When equal to 1,  WHERE (SELECT COUNT(1) FROM b WHERE A.ID = B.ID) = 0; is false. So when taking values ​​from a in order, as long as the expression exists in b, this expression is false, so it cannot be taken out from a.

Except for a, the ids in b are equal. In all remaining cases, count(1) is 0, and WHERE (SELECT COUNT(1) FROM b WHERE A.ID = B.ID) = 0; is true. There is no limit to the value of a.

You see that I count a data that does not exist in the b table and return 0

 

Reference: http://blog.csdn.net/windren06/article/details/8188136

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325139449&siteId=291194637