PostgreSQL 按字符串查询甚至过滤有空值的值。

PostgreSQL query by string is filtering even the values where there are nulls.

我在 PostgreSQL 9.5 中创建了一个 table,如下所示,并向其中添加了一些数据。但是,当我尝试通过像 !~* 这样不区分大小写的搜索来查询数据时,它甚至会删除空值行。我怎样才能做一个查询,将 return 所有 null 和 vegetable 但不是 fruit 的类别?

CREATE TABLE temp
(
  category character varying,
  item character varying
);

INSERT INTO temp VALUES('Fruits', 'apple');
INSERT INTO temp VALUES('FRUITS', 'applE');
INSERT INTO temp(item) VALUES('Apple');
INSERT INTO temp(item) VALUES('BANANA');
INSERT INTO temp VALUES('Vegetables', 'Cabbage');

查询

Select * from temp where category !~* 'fruits'

输出

category   item
--------   --------
Vegetables Cabbage

要处理空值,您可以使用 is distinct from:

Select * 
from temp 
where lower(category) is distinct from 'fruits'

或者如果您确实需要正则表达式:

Select * 
from temp 
where category !~* 'fruits'
  or category is null;

或者将 null 视为其他内容:

Select * 
from temp 
where coalesce(category, '') !~* 'fruits'