检查文本列数组是否包含包含短语的字符串
Check if the array of text column contains string containing phrase
我有一个 table customers
结构如下:
id: int
products: text[]
我想创建 SQL 查询来检查是否有名称包含词组“a”但不包含词组“b”的产品,所以基本上:
product ILIKE "%a%" AND product NOT ILIKE "%b%"
如果我想检查元素是否存在,那么它就像使用 @>
运算符一样简单,但在这里我尝试了 UNNEST
和许多不同的方法,但似乎没有任何效果。
我只想根据此条件包含或不包含给定的客户行。你能帮忙吗?
我试过类似的东西:
SELECT
*
FROM
customers,
UNNEST(products) AS product
WHERE
product ILIKE '%a%' AND product NOT ILIKE '%b%';
或
SELECT
*
FROM
customers
LEFT JOIN LATERAL (
SELECT * FROM UNNEST(products) AS element
) AS products2 ON TRUE
WHERE
element ILIKE '%a%' AND element NOT ILIKE '%b%';
理论上我可以这样做:
products::TEXT ILIKE '%a%' AND products::TEXT NOT ILIKE '%b%'
但这是一个并不总是奏效的丑陋技巧
我会推荐:
select c.*
from customers c
where exists (select 1
from unnest(c.products) p
where p like '%a%'
) and
not exists (select 1
from unnest(c.products) p
where p like '%b%'
);
您可以使用单个 unnest 执行此操作。只是看起来更复杂:
select c.*
from customers c
where (select countif(p like '%a%') = count(*) and
countif(p like '%b%') = 0
from unnest(c.products) p
where p like '%a%' or p like '%b%'
) ;
我有一个 table customers
结构如下:
id: int
products: text[]
我想创建 SQL 查询来检查是否有名称包含词组“a”但不包含词组“b”的产品,所以基本上:
product ILIKE "%a%" AND product NOT ILIKE "%b%"
如果我想检查元素是否存在,那么它就像使用 @>
运算符一样简单,但在这里我尝试了 UNNEST
和许多不同的方法,但似乎没有任何效果。
我只想根据此条件包含或不包含给定的客户行。你能帮忙吗?
我试过类似的东西:
SELECT
*
FROM
customers,
UNNEST(products) AS product
WHERE
product ILIKE '%a%' AND product NOT ILIKE '%b%';
或
SELECT
*
FROM
customers
LEFT JOIN LATERAL (
SELECT * FROM UNNEST(products) AS element
) AS products2 ON TRUE
WHERE
element ILIKE '%a%' AND element NOT ILIKE '%b%';
理论上我可以这样做:
products::TEXT ILIKE '%a%' AND products::TEXT NOT ILIKE '%b%'
但这是一个并不总是奏效的丑陋技巧
我会推荐:
select c.*
from customers c
where exists (select 1
from unnest(c.products) p
where p like '%a%'
) and
not exists (select 1
from unnest(c.products) p
where p like '%b%'
);
您可以使用单个 unnest 执行此操作。只是看起来更复杂:
select c.*
from customers c
where (select countif(p like '%a%') = count(*) and
countif(p like '%b%') = 0
from unnest(c.products) p
where p like '%a%' or p like '%b%'
) ;