【问题标题】:How do I exclude from array in postgresql?如何从 postgresql 中的数组中排除?
【发布时间】:2018-06-04 16:36:31
【问题描述】:

我想在下面的查询中更改数组列 call_type 的条件,以便它排除所有具有“访问发生”的内容。
我如何使用该数组部分?

select staff_id,
   COUNT(event_id) as offered
from call_logs as logs
where visit_offered
and contact_date between now() - interval '1 weeks' and now()
and provider_type = 'Contractor'
and contact_with != 'company_staff'
and direction = 'outbound'
and outcome = 'Successful'
and call_type && array  ['Schedule','schedule_visit']
group by staff_id;

【问题讨论】:

  • "排除所有有 'visit_occurred'" 有点模糊。您想完全匹配数组元素还是识别包含给定字符串的元素?请始终公开您的 Postgres 版本。

标签: sql arrays postgresql


【解决方案1】:

要简单地将数组元素作为一个整体进行匹配,请使用ARRAY contains operator @>,取反:

AND  NOT call_type @> '{schedule_visit}'::text[]

注意数组包装器。通常不需要转换为 text[],但有助于避免歧义。

如果该列可以是NULL,并且您不想排除此类行:

AND  (call_type @> '{schedule_visit}'::text[]) IS NOT TRUE

可以支持索引:

模式匹配更加复杂。使用NOT EXISTS 表达式:

AND NOT EXISTS (
   SELECT FROM unnest(logs.call_type) call
   WHERE  call ILIKE '%visit_occurred%'  -- case insensitive?
   )

对此没有索引支持。 JSON数组的相关答案(原理相同):

另一种方法是将您的数组列标准化为单独的 n:1 表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 2019-05-12
    • 2016-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多