如何测试 int2vector 是否恰好包含一个特定值?

How can I test if int2vector contains exactly one specific value?

我当前的代码如下所示:

SELECT
  1
FROM pg_namespace   sch
JOIN pg_class       tab ON tab.relnamespace = sch.oid
JOIN pg_index       idx ON idx.indrelid     = tab.oid
JOIN pg_class       icl ON icl.oid          = idx.indexrelid
JOIN pg_attribute   col ON col.attrelid     = tab.oid
WHERE
      sch.nspname      = 'my_schema'
  AND tab.relkind      = 'r'
  AND idx.indisprimary
  AND icl.relname      = 'pk_my_table'
  AND col.attname      = 'my_table_id'
  AND idx.indkey       = ARRAY[col.attnum] -- <-- The problematic comparison
;

这行不通,因为:ERROR: operator does not exist: int2vector = smallint[].

我尝试了各种组合:

如何检查 indkey 是否恰好包含一个正好是 col.attnum 的条目?

您可以转换为 text 并转换为 integer 数组:

AND string_to_array(idx.indkey::text, ' ')::int2[] = ARRAY[col.attnum]

实际上,由于 pg_attribute.attnumsmallint (int2),所以使用 int2[].

并且由于您只对单个列感兴趣,您可以简化:

AND idx.indkey::text = col.attnum::text

SQL Fiddle.

在索引中处理 多列 时要小心。考虑这个相关的答案:

  • How to find whether unique key constraint exists for given columns