如何通过JOIN从另一个表中查找不存在的数据?

2021-11-20 00:00:00 join sql mysql anti-join

我有两个表 TABLE1,它看起来像:

I have two tables TABLE1 which looks like:

id      name     address
1       mm     123
2       nn     143

和 TABLE2 w/c 看起来像:

and TABLE2 w/c looks like:

name     age
mm      6
oo      9

我想通过比较 TABLE1TABLE2 来获取不存在的名称.

I want to get the non existing names by comparing the TABLE1 with the TABLE2.

所以基本上,我必须得到第二行,w/c 有一个在 TABLE2 中不存在的 NN 名称,输出应如下所示:

So basically, I have to get the 2nd row, w/c has a NN name that doesn't exist in the TABLE2, the output should look like this:

id      name     address
2      nn      143

我试过了,但没有用:

SELECt  w.* FROM TABLE1 W INNER JOIN TABLE2 V
  ON W.NAME <> V.NAME

它仍在获取现有记录.

推荐答案

INNER JOIN 在这里没有帮助.

解决这个问题的一种方法是使用LEFT JOIN:

One way to solve this is by using a LEFT JOIN:

SELECT w.* 
FROM TABLE1 W 
LEFT JOIN TABLE2 V ON W.name = V.name
WHERE ISNULL(V.name);

相关文章