我在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
。这是为什么?
答案 0 :(得分:3)
除了IS NOT NULL
之外,使用IS NULL
AND =''
将确保您获得的所有行都是空的,就像您要查找的那样或将列设置为NULL
SELECT count(*) FROM keeper WHERE code!='' OR code IS NOT NULL;
SELECT count(*) FROM keeper WHERE code = '' OR code IS NULL
答案 1 :(得分:0)
始终使用IS NuLL
ans IS 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
将为您提供代码为“空”值的所有记录,将NULL视为空。
答案 2 :(得分:0)
NULL和&#34;&#34;是两件不同的事情。 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;
这三个结果应该合计为表格中的总行数。
答案 3 :(得分: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)。