简体   繁体   中英

SQL query comparison between two tables

I have two tables in my database:

table_A:             table_B:                  

id    user           id    user               
1     Mike           1     Mike          
2     Dan            2     Dan           
3     Tom            3     Tom
4     Lina           4     Lina
                     5     Cynthia
                     6     Sam

My aim is to identify which users in Table_B do not exist in Table_A based on id. I'm new in SQL, and this is what i came up with:

SELECT id FROM Table_B
WHERE B.id NOT IN ( SELECT A.id from Table_A)

Most likely my logic is wrong, so i'd appreciate any guidance please.

You can use sub-query in WHERE clause predicate NOT IN Then it will return the id present in table_B only

Sub-Query

This query return id from table_A

SELECT table_A.id FROM table_A

Then it will be passed to NOT IN clause which will return boolean true on every record set iteration if not matched. So id 5 and 6 only return in the main query.

Final Query

SELECT table_B.id, table_B.name FROM table_B WHERE table_B.id NOT IN (SELECT table_A.id FROM table_A);

OR

to select all column use symbol * instead of column lists

SELECT * FROM table_B WHERE table_B.id NOT IN (SELECT table_A.id FROM table_A);

您可以使用EXISTS功能。

Select * from table_B where Not EXISTS (select * from table_A)

You are close. It seems to me that the only thing you need to change is the A.ID and B.ID reference

SELECT id FROM Table_B B
WHERE B.id NOT IN ( SELECT A.id from Table_A A)

Since you are referring to Table_A as A and table_B as B you need to create the alias name.

You could also use

SELECT id FROM Table_B B
WHERE NOT EXISTS ( SELECT A.id from Table_A A where A.ID = B.ID)

but i would prefer the first one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM