English 中文(简体)
COUNT()与NOT IN(NOTIN)条款有关的功能,与Valchar油田(T-SQL)不适当合作
原标题:COUNT() Function in conjunction with NOT IN clause not working properly with varchar field (T-SQL)

当尝试通过select语句来计算没有指定varchar值的行数时,我遇到了一个奇怪的情况。好吧,听起来甚至对我自己来说也很困惑,所以让我给你举个例子:

Let s say I have a field "MyField" in "SomeTable" and I want to count in how many rows MyField values do not belong to a domain defined by the values of "MyOtherField" in "SomeOtherTable". In other words, suppose that I have MyOtherField = {1, 2, 3}, I wanna count in how many rows MyField value are not 1, 2 or 3. For that, I d use the following query:

SELECT COUNT(*) FROM SomeTable   
WHERE ([MyField] NOT IN (SELECT MyOtherField FROM SomeOtherTable))   

而且它工作得非常好。请注意,MyField和MyOtherField是int类型的。如果我尝试运行完全相同的查询,除了varchar类型的字段之外,它返回的值为0,即使我知道有错误的值,我也把它们放在那里!如果我试图计算相反的(域中有多少行与我要求的相反,即有多少行不是),只需在上面的查询中压制“NOT”子句...那么,那篇文章! ¬¬

是的,肯定有许多解决办法,但我想知道为什么它不能像应该的那样工作。此外,我不能简单地改变整个查询,因为大部分都是在C#代码中构建的,基本上我能够自由更改的仅是对应于域的select语句(在NOT IN子句中发生的任何事情都不会对其他软件的任何其他部分产生影响)。我希望我表达清楚,希望有人能帮助我。

提前致谢。

最佳回答

对于“NOT IN”,如果子查询返回一个NULL值,它将始终为false。在这个问题中,被接受的答案优雅地描述了原因。

单面值的可变性与所使用的数据类型无关:最有可能的是,您的千篇一律的列数中都有联合国法语大学的数值。

为处理此事,请使用NOT EXISTS。对于非空值,它的工作方式与NOT IN相同,因此是兼容的。

SELECT COUNT(*) FROM SomeTable S1 
WHERE NOT EXISTS (SELECT * FROm SomeOtherTable S2 WHERE S1.[MyField] = S2.MyOtherField)   
问题回答

GBN有一个更完整的答案,但我懒得记住那么多。相反,我有一个宗教习惯,即从我的IN语句中过滤掉null值。

SELECT COUNT(*)
FROM SomeTable    
WHERE [MyField] NOT IN (
  SELECT MyOtherField FROM SomeOtherTable
  WHERE MyOtherField is not null
)




相关问题
How to write this T-SQL WHERE condition?

I ve got two tables: TableA Col1 Col2 TableB Col3 Col4 I want to join them together: SELECT * from TableA join TableB ON (...) Now, in place of ... I need to write an expression ...

Customer and Order Sql Statement

TSQL query to select all records from Customer that has an Order and also select all records from customer that does not have an Order. The table Customer contains a primary key of CustomerID. The ...

Recommended way of querying multiple Versioned tables

Have a win 2003 box with MSSQL 2005 running on it. There is a database which is populated every morning with new/modified SalesOrder made the previous day. The database has several tables: SalesOrder, ...

update duplicate record

I have a table with the following fields Id Name IsPublic i need to write a sql query that updates IsPublic to false where name has a duplicate. Only one of the duplicates should have IsPublic = ...

Define variable to use with IN operator (T-SQL)

I have a Transact-SQL query that uses the IN operator. Something like this: select * from myTable where myColumn in (1,2,3,4) Is there a way to define a variable to hold the entire list "(1,2,3,4)"? ...

Selecting records during recursive stored procedure

I ve got a content management system that contains a hierarchical structure of categories, with sub-categories subject to different ordering options at each level. Currently, that s retrieved by a (...

热门标签