具有多个 'not in' 检查的 SQL where 子句

标签 sql sql-server sql-server-2005 t-sql

这看起来应该是一个相对简单的查询,但有人可以解释一下为什么第二个查询不返回第 2 行和第 3 行,但第三个查询却返回行?基本上,如何使查询满足两个“not in”子句?

declare @t table (id int identity, code1 char(2), code2 char(2))

insert into @t (code1, code2) values ('AA','BB')
insert into @t (code1, code2) values ('AA','CC')
insert into @t (code1, code2) values ('DD','EE')

select * from @t where code1 = 'AA' and code2 = 'BB'
select * from @t where (code1 != 'AA' and code2 != 'BB')
select * from @t t1 left join @t t2 on t2.id = t1.id and t2.code1 = 'AA' and t2.code2 = 'BB' where t2.id is null

* 已更新*

感谢您的回答。我希望“(code1 != 'AA' and code2 != 'BB')”都需要评估,即第1行(AA,BB)将被过滤掉,但rwo 2(AA,CC)将被过滤掉被退回。

是否没有简单的方法来规定需要满足两个约束,这就是我希望通过使用括号和 and 语句来实现的?

最佳答案

对于查询 2,第二行的 code1 != 'AA' 为 FALSE。

关于具有多个 'not in' 检查的 SQL where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4226495/

相关文章:

java - 打印失败行 PreparedStatement addBatch

sql - 如何在单个查询中使用 count ,'like' 和 group by?

sql-server - SISS - 将 DT_STR 转换为 DT_DECIMAL 的问题(小数部分变为整数部分编号)

sql-server - Azure数据库: create table if not exists

c# - 将数据库中的值显示到文本框

SQL-临时表 : Storing all columns in temp table versus only Primary key

jquery - 先进的 ASP.NET 提高性能

sql - 我想使用 union all 进行插入,其中有一列从序列中获取值

mysql - 在 1 中优化许多 SQL 请求

sql - 如何在 sql server 2005 中使用 sql 查询更改表中的列顺序?