简体   繁体   中英

MySQL: selecting data not in common between two tables

I have table1 with 3 numbers and table2 with 1 number:

table1       table2
n              n
1              1
2
3

I want to select data from table1 that is NOT present in table2 (numbes 2 and 3). I tried:

select table1.* from table1, table2 where table1.n <> table2.n

I also tried other where clauses:

where table1.n not like table2.n
where not table1.n = table2.n

But I don't get the results. I know it can be done in multiple steps, but I wonder if there is a simple query to do it. Thanks

You need to do a LEFT JOIN and look for null values for t2. Like this:

SELECT
   t1.n
FROM
   table1 AS t1
   LEFT JOIN table2 AS t2
     ON t1.n = t2.n
WHERE
    t2.n IS NULL

Here is link to a great reference for different sorts of JOINS which includes Venn diagrams to help you visualize the different approaches to joining.

http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/

You can do that using NOT IN or NOT EXISTS.

select * from table1
where table1.n not in (select table2.n from table2);

select * from table1
where  not exists (select table2.n from table2 where table2.n = table1.n);

I tried both approaches (left join and not in) several times and it took the exact same time (my table is pretty big). Thanks guys!

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