简体   繁体   English

Informix SQL-简单选择查询返回意外结果

[英]Informix SQL - Simple select query is returning unexpected results

Follow this, it's really obvious and simple. 遵循此步骤,这确实非常简单。 For some reason, the results differ between queries and approach angles on data subsets. 由于某些原因,结果在查询和数据子集的进场角度之间会有所不同。 Keep in mind that the field, correct_addr is a char(1) field with allowable nulls. 请记住,字段correct_addr是一个char(1)字段,其中包含允许的空值。

select distinct correct_addr, count(*) from id_rec group by correct_addr;

correct_addr       (count(*))
                         2477
N                          80
Y                       84013

3 row(s) retrieved.

Ok, so correct_addr contains 3 distinct values: "N","Y", and either "" or " " or NULL 好的,因此correct_addr包含3个不同的值:“ N”,“ Y”以及“”,“”或NULL

So now, I try this: 所以现在,我尝试一下:

select count(*) from id_rec where correct_addr <> 'N';

      (count(*))
           84013

What happened to the 2477 records that have that blank value? 具有该空白值的2477条记录发生了什么?

Another try from a different angle: 从另一个角度尝试另一种方法:

select count(*) from id_rec where correct_addr in (null,'',' ','Y');

      (count(*))
           84013

Same thing happens.... 发生同样的事情。

So what is going on here? 那么这里发生了什么? Why doesn't the sql engine (?) recognize the blank value in the last 2 sql statements? 为什么sql引擎(?)不能识别最后2条sql语句中的空白值? It discovers it fine in the first query with the grouping, but nowhere else. 它在具有分组的第一个查询中发现很好,但是没有其他地方。

Does anyone have any ideas as to why this type of thing happens? 是否有人对为什么发生这种事情有任何想法?

NULLs require special handling in SQL. NULLs需要在SQL中进行特殊处理。

Try 尝试

select count(*) 
from id_rec 
where correct_addr <> 'N' 
    or correct_addr is null; 

See here for an explanation of handling NULLs . 有关处理NULL的说明,请参见此处

NULL comparisons are always false. NULL比较始终为假。 And empty string or single space is a value which is not NULL. 空字符串或单个空格是一个不为NULL的值。

However, GROUP BY will recognise it and count it. 但是,GROUP BY将识别并计数。

Try these 试试这些

select count(*) from id_rec
where correct_addr <> 'N' or correct_addr IS NULL

select count(*) from id_rec
where COALESCE(correct_addr, 'X') <> 'N' 


select count(*) from id_rec
where COALESCE(correct_addr, ' ') in (' ','Y');

Also, COUNT(column) will ignore NULLS so some more to try 另外,COUNT(column)将忽略NULLS,因此可以尝试更多

select count(correct_addr), COUNT(*) from id_rec GROUP BY correct_addr

select count(correct_addr), COUNT(*) from id_rec
where correct_addr <> 'N' or correct_addr IS NULL

Note: char(1) will always pad to a space 注意:char(1)将始终填充到空格

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM