评估数组是否包含给定元素以外的元素
Evaluate whether an array contains an element other than given elements
我正在尝试确定我的给定数组 _servicetype
是否包含 12,1,2,3 以外的元素。
以下是我目前所拥有的,
场景 1:如果我的数组是 {1,2,3,6015} 我想要 FALSE
场景 2:如果我的数组是 {1,2,12} 我想要 TRUE
场景 3:如果我的数组是 {1,2} 我想要 true
我最终在 Postgres 中将 iif 语句创建为用户定义的函数,并得到以下内容:
IIF(_servicetype@>ARRAY['12']::INT[]
OR _servicetype@>ARRAY['1'] ::INT[]
OR _servicetype@>ARRAY['2'] ::INT[]
OR _servicetype@>ARRAY['3'] ::INT[],TRUE,FALSE)::BOOLEAN
我担心它不适用于场景 1。
您可以使用 @>
(contains/covers) 运算符检查 ARRAY[12, 1, 2, 3]
是 _servicetype
的超集,即如果 _supertype
包含任何不在ARRAY[12, 1, 2, 3]
return false
:
WITH examples(_servicetype) AS (
VALUES
('{1,2,3,6015}'::int[]),
('{2,1}'::int[]),
('{1}'::int[])
)
SELECT _servicetype, '{12, 1, 2, 3}' @> _servicetype
FROM examples;
┌──────────────┬──────────┐
│ _servicetype │ ?column? │
├──────────────┼──────────┤
│ {1,2,3,6015} │ f │
│ {2,1} │ t │ -- set-wise "contains", order does not matter
│ {1} │ t │
└──────────────┴──────────┘
(3 rows)
我正在尝试确定我的给定数组 _servicetype
是否包含 12,1,2,3 以外的元素。
以下是我目前所拥有的,
场景 1:如果我的数组是 {1,2,3,6015} 我想要 FALSE
场景 2:如果我的数组是 {1,2,12} 我想要 TRUE
场景 3:如果我的数组是 {1,2} 我想要 true
我最终在 Postgres 中将 iif 语句创建为用户定义的函数,并得到以下内容:
IIF(_servicetype@>ARRAY['12']::INT[]
OR _servicetype@>ARRAY['1'] ::INT[]
OR _servicetype@>ARRAY['2'] ::INT[]
OR _servicetype@>ARRAY['3'] ::INT[],TRUE,FALSE)::BOOLEAN
我担心它不适用于场景 1。
您可以使用 @>
(contains/covers) 运算符检查 ARRAY[12, 1, 2, 3]
是 _servicetype
的超集,即如果 _supertype
包含任何不在ARRAY[12, 1, 2, 3]
return false
:
WITH examples(_servicetype) AS (
VALUES
('{1,2,3,6015}'::int[]),
('{2,1}'::int[]),
('{1}'::int[])
)
SELECT _servicetype, '{12, 1, 2, 3}' @> _servicetype
FROM examples;
┌──────────────┬──────────┐
│ _servicetype │ ?column? │
├──────────────┼──────────┤
│ {1,2,3,6015} │ f │
│ {2,1} │ t │ -- set-wise "contains", order does not matter
│ {1} │ t │
└──────────────┴──────────┘
(3 rows)