SQL查询查找ID不在另一个表中的记录 [英] SQL query to find record with ID not in another table

查看:1101
本文介绍了SQL查询查找ID不在另一个表中的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个绑定主键的数据库表,我希望找到它们之间的不相交集合。例如,

I have two tables with binding primary key in database and I desire to find a disjoint set between them. For example,


  • Table1 有列(名称)和示例数据:(1,John),(2,Peter),(3,Mary)

  • 表2 有列( ID,地址)和示例数据: ,address2),(2,address2)

  • Table1 has columns (ID, Name) and sample data: (1 ,John), (2, Peter), (3, Mary)
  • Table2 has columns (ID, Address) and sample data: (1, address2), (2, address2)

那么如何创建一个SQL查询从 table1 中获取不在 table2 中的ID的行。在这种情况下,应该返回(3,Mary)

So how do I create a SQL query so I can fetch the row with ID from table1 that is not in table2. In this case, (3, Mary) should be returned?

Ps。 ID是这两个表的主键。

Ps. The ID is the primary key for those two tables.

提前感谢。

推荐答案



Try this

SELECT ID, Name 
FROM   Table1 
WHERE  ID NOT IN (SELECT ID FROM Table2)

这篇关于SQL查询查找ID不在另一个表中的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆