0

我在 MySQL 中运行了三个 SQL 查询,但存在逻辑问题。

select count(*) from keeper where code!=''; -- result1=2893193
select count(*) from keeper where code=''; -- result2=66
select count(*) from keeper; -- result3=3481069

我预料到了result1 + result2 = result3,但事实上,result1 + result2 < result3。为什么是这样?

4

4 回答 4

3

使用IS NOT NULLANDIS NULL除了=''将确保您获得所有空行,就像您正在寻找的那样,或者将列设置为 NULL

SELECT count(*) FROM keeper WHERE code!='' OR code IS NOT NULL;
SELECT count(*) FROM keeper WHERE code = '' OR code IS NULL
于 2012-04-08T04:56:38.710 回答
0

始终使用IS NuLLansIS NOT NULL分别获取准确的空记录和非空记录。它检查空值和空值。

试试下面:

select count(*) from keeper where code is NULL;

select count(*) from keeper where code is NOT NULL

或者,您可以使用:

select  count(*) from keeper where LENGTH(COALESCE(code ,'')) = 0

将为您提供所有带有“空”值的记录 code ,将 NULL 视为空。

于 2012-04-08T04:55:20.517 回答
0

三值逻辑攻击!

NULL 和 "" 是两个不同的东西。NULL 被认为既不等于也不不等于"",因此您的任何查询都不会返回它。我猜您的第三个查询返回的额外 500,000 条记录已code设置为 NULL。IS NULL您可以使用或测试空字段IS NOT NULL。如果你这样做:

SELECT count(*) from keeper where code!='';
SELECT count(*) from keeper where code='';
SELECT count(*) from keeper where code IS NULL;

这三个结果应该加起来就是表中的总行数。

于 2012-04-08T04:58:56.047 回答
0
1.   select count(*) from keeper where code!=''
2.   select count(*) from keeper where code=''
2.5. select count(*) from keeper where code is null
3.   select count(*) from keeper

注意之前插入的那个3。NULL 被视为与任何其他值不同的情况,既不等于也不等于任何其他值(包括另一个 NULL)。

于 2012-04-08T05:00:01.110 回答