關于NULL
更新時間 2025-02-14 10:22:03
最近更新時間: 2025-02-14 10:22:03
分享文章
本頁介紹天翼云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)