【问题标题】:Where array does not contain value Postgres其中数组不包含值 Postgres
【发布时间】:2014-11-18 01:30:20
【问题描述】:

我正在使用 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

我想用 ' > ' 排除结果

【问题讨论】:

  • 您有一个名为categoriestext[],其中包含类似这四个字符串的内容,并且您想过滤掉包含'>' 的数组条目?所以你最终会得到一个像array['Women''s', 'Men''s']这样的数组?
  • 一如既往地,请问您的 Postgres 版本?你真的想取消嵌套数组(这样每个元素都有 1 行),还是这只是你的测试尝试?
  • 谢谢! Postgres 9.3.4 如果我不取消嵌套,结果会将类别数组中的所有内容聚集在一起。
  • 那么您是否希望结果不嵌套?
  • 抱歉,我需要一个未嵌套的结果。

标签: sql arrays postgresql pattern-matching unnest


【解决方案1】:

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

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

NOT EXISTS 半连接中使用unnest() 的简洁优雅的解决方案

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.

【讨论】:

  • 宾果游戏!在选择中使用了第一个但未嵌套的类别。像魅力一样工作。
【解决方案2】:

计算'>' 字符在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

【讨论】:

  • 得到错误“函数长度(字符变化[])不存在”
  • 可以将unnest(categories) 选入临时表吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-14
  • 1970-01-01
  • 1970-01-01
  • 2017-07-05
  • 2020-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多