首页 > 解决方案 > 不等于运算符在 SQL Select 语句中不起作用

问题描述

我有两个表 A 和 B 包含相同的 Id(不是两个表中的主键),我只想获取表 A 中存在的数据。

表 A:

Id

1
2
555
6 

表 B

Id

1
2
1
2
1
2

查询语句

select distinct o.Id from  Table A o,Table B ot where o.isActive=1 and not(ot.Id=o.Id)

这将返回表 A 中存在的相同数据,但预期结果应为:

Id

555
 6

我怎样才能得到这个作品?

标签: sqlsql-server

解决方案


下面是一种方法。我还添加了一个条件以确保表 B 中的 Id 字段中存在合法值,因为您说它不是标识列。

select distinct Id
from Table A
where Id not in
    (select Id
    from Table B
    where Id > 0)

推荐阅读