將WHERE子句與NOT LIKEon一起使用時my_text_column,null將跳過值。
為什么以及如何獲得它?
SELECT count(id) FROM public.mytable;
count
-------
91
SELECT count(id) FROM public.mytable WHERE my_text_column LIKE 'foo';
count
-------
59
SELECT count(id) FROM public.mytable WHERE my_text_column NOT LIKE 'foo';
count
-------
0
uj5u.com熱心網友回復:
SQL 標準對 Framework 4.4.2 中的 NULL 進行了說明:
[...]的空值既不等于為任何其他值,也沒有不等于任何其它值-它是未知它是否等于任何給定值[...]
在 4.4.3.3 中它說:
所述的值的布爾資料型別將是真或假。未知的真值有時用空值表示。
它以一種古怪的方式表示,將某些內容與 NULL 值進行比較將導致 NULL。可以這樣想:未知字串是否像foo.
有幾種方法可以得到你想要的東西:
使用
coalesce:WHERE coalesce(my_text_column, 'foo') LIKE 'foo%'使用
OR:WHERE my_text_column LIKE 'foo%' OR my_text_column IS NULL使用
UNION ALL:SELECT count(id) FROM (SELECT id FROM public.mytable WHERE my_text_column LIKE 'foo%' UNION ALL SELECT id FROM public.mytable WHERE my_text_column IS NULL) AS subq;
像這樣的查詢使索引變得復雜。
uj5u.com熱心網友回復:
SELECT count(*) FROM public.mytable
WHERE my_text_colum not LIKE 'foo' or my_text_colum is null;
從手冊:
如果模式不包含百分號或下劃線,則模式僅代表字串本身;在這種情況下, LIKE 的作用類似于等號運算子。
所以SELECT count(*) FROM tbl3 WHERE txt <> 'foo' or txt is null;也有效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/366098.html
標籤:PostgreSQL的
