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

Jen*_*off 3 sql arrays postgresql comparison types

我当前的代码如下所示:

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
;
Run Code Online (Sandbox Code Playgroud)

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

我尝试了以下各种组合:

  • 转换indkey为数组,例如idx.indkey::smallint[]
  • 投射ARRAY[col.attnum]int2vector
  • 使用ALL运算符
  • 使用@>运算符

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

Erw*_*ter 5

您可以转换textinteger数组:

AND string_to_array(idx.indkey::text, ' ')::int2[] = ARRAY[col.attnum]
Run Code Online (Sandbox Code Playgroud)

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

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

AND idx.indkey::text = col.attnum::text
Run Code Online (Sandbox Code Playgroud)

SQL 小提琴。

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