其中数组不包含值Postgres

时间:2014-09-23 18:11:20

标签: sql arrays postgresql pattern-matching unnest

我使用postgres来提取一些数据。我有一个数组(类别),我想要排除包含' > '

select title, short_url, unnest(categories) as cats, winning_offer_amount
from auctions
where ended_at is not null
and '% > %' NOT IN cats
group by title, short_url, cats, winning_offer_amount

我意识到我的语法是完全错误的,但试图让我知道我想要写什么。结果可能是:

Women's > Shoes
Women's
Men's > Shoes
Men's

我想用'排除结果。 > '

2 个答案:

答案 0 :(得分:2)

一种简单的“强力”方法是将数组强制转换为text 并检查:

SELECT title, short_url, categories, winning_offer_amount
FROM   auctions
WHERE  ended_at IS NOT NULL
AND    categories::text NOT LIKE '% > %';  -- including blanks?

unnest()半合并中 NOT EXISTS的简洁优雅解决方案:

SELECT title, short_url, categories, winning_offer_amount
FROM   auctions a
WHERE  ended_at IS NOT NULL
AND    NOT EXISTS (
   SELECT 1
   FROM   unnest(a.categories) AS cat
   WHERE  cat LIKE '% > %'
   );

SQL Fiddle.

答案 1 :(得分:0)

计算'>'字符在cats中出现的次数,如果计数等于零,则仅包括记录。

所以,像这样(检查确切的语法):

select title, short_url, unnest(categories) as cats, winning_offer_amount
from auctions
where ended_at is not null
and (length(cats) - length(replace(cats, '>', '')))=0 
group by title, short_url, cats, winning_offer_amount