简体   繁体   English

MySQL:选择两个表之间不通用的数据

[英]MySQL: selecting data not in common between two tables

I have table1 with 3 numbers and table2 with 1 number: 我有3个数字的table1和1个数字的table2:

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). 我想从表1中选择表2中不存在的数据(数字2和3)。 I tried: 我试过了:

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

I also tried other where clauses: 我还尝试了其他where子句:

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. 您需要执行LEFT JOIN并查找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. 这是指向各种JOINS的出色参考的链接,其中包括Venn图,以帮助您可视化不同的联接方法。

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

You can do that using NOT IN or NOT EXISTS. 您可以使用NOT IN或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! 多谢你们!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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