问题描述
customers
我想创建 sql 查询来检查是否存在名称包含短语“a”但不包含短语“b”的产品,因此基本上:
id: int
products: text[]
如果我想检查元素是否存在,那么它就像使用 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%';
但这是一个丑陋的黑客,并不总是有效
解决方法
我会推荐:
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%'
) ;