关于 NULL
 
                  更新时间 2025-02-14 10:22:19
                 
 
                    最近更新时间: 2025-02-14 10:22:19
                  
 本页介绍天翼云TeleDB数据库中关于NULL的判断和处理方案。
 - NULL的判断:IS NULL,IS NOT NULL。 - 注意 - boolean 类型取值 true,false,NULL。 - NOT IN 集合中带有 NULL 元素。 - teledb=# select * from t_oids; id | name | birth | city ----+------+---------------------+------ 1 | 张三 | 2000-12-01 00:00:00 | 北京 2 | 李四 | 1997-03-24 00:00:00 | 上海 3 | 王五 | 2004-09-01 00:00:00 | 广州 (3 rows) teledb=# select * from t_oids where id not in (null); id | name | birth | city ----+------+-------+------ (0 rows)
- 建议对字符串型NULL 值处理后,再进行 || 操作。 - teledb=# select id,name from t_oids limit 1; id | name ----+------ 1 | 张三 (1 row) teledb=# select id,name||null from t_oids limit 1; id | ?column? ----+---------- 1 | (1 row) teledb=# select id,name|| coalesce(null,'') from t_oids limit 1; id | ?column? ----+---------- 1 | 张三 (1 row)- 注意 - 开启oracle兼容后,可无需处理。 - teledb=# set enable_oracle_compatible to on; SET teledb=# select id,name||null from t_oids limit 1; id | ?column? ----+---------- 1 | 张三 (1 row)
- 建议使用count(1) 或 count(*) 来统计行数,而不建议使用 count(col) 来统计行数,因为 NULL 值不会计入。 - 说明 - count(多列列名)时,多列列名必须使用括号,例如count( (col1,col2,col3) ),注意多列的count,即使所有列都为NULL,该行也被计数,所以效果与count(*)一致。 - teledb=# select * from t_oids ; id | name | birth | city ----+------+---------------------+------ 1 | 张三 | 2000-12-01 00:00:00 | 北京 2 | 李四 | 1997-03-24 00:00:00 | 上海 3 | 王五 | 2004-09-01 00:00:00 | 广州 4 | 陈六 | 2022-01-01 00:00:00 | (4 rows) teledb=# select count(city) from t_oids; count ------- 3 (1 row) teledb=# select count(1) from t_oids; count ------- 4 (1 row) teledb=# select count(*) from t_oids; count ------- 4 (1 row) teledb=# select count(id) from t_oids; count ------- 4 (1 row) teledb=# select count((id,city)) from t_oids; count ------- 4 (1 row)
- count(distinct col) 计算某列的非 NULL 不重复数量,NULL 不被计数。 - count(distinct (col1,col2,...) ) 计算多列的唯一值时,NULL 会被计数,同时 NULL 与 NULL 会被认为是相同的。 teledb=# select count(distinct city) from t_oids; count ------- 3 (1 row) teledb=# select count(distinct (id, city)) from t_oids; count ------- 4 (1 row)
- 两个NULL 的对比方法。 - teledb=# select null is not distinct from null; ?column? ---------- t (1 row)
