从第一张表中获取不匹配的记录

时间:2017-05-24 05:24:07

标签: mysql

我有两张桌子:

表1:

+---------------------+
|id  |  name | company|
+---------------------+ 
|1   |  sai  |  abc   |
|2   |  sri  |  xyz   |
|4   |  abx  |  bcd   |
+---------------------+

表2:

+---------------------------+
| id  |  emp_name |  salary |
+---------------------------+
| 1   |     sai   |   20k   |
| 4   |     abx   |   40k   |
+---------------------------+

当比较两个表时,table1的不匹配数据才会出现。

结果:

+----------------------+
|id  | name  | company |
+----------------------+
|2   |  sri  |   xyz   |
+----------------------+

我尝试过:

SELECT * FROM Table1 a WHERE NOT EXISTS (SELECT * FROM Table2 b WHERE a.id = b.id)

1 个答案:

答案 0 :(得分:0)

一个选项使用LEFT JOIN

SELECT t1.*
FROM Table1 t1
LEFT JOIN Table2 t2
    ON t1.id = t2.id
WHERE t2.id IS NULL

在这里演示:

Rextester