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]到int2vectorALL运算符@>运算符如何检查是否indkey恰好包含一个条目col.attnum?
您可以转换text为integer数组:
AND string_to_array(idx.indkey::text, ' ')::int2[] = ARRAY[col.attnum]
Run Code Online (Sandbox Code Playgroud)
实际上,由于pg_attribute.attnum是smallint( int2),因此使用int2[].
由于您只对单个列感兴趣,因此您可以简化:
AND idx.indkey::text = col.attnum::text
Run Code Online (Sandbox Code Playgroud)
处理索引中的多列时要小心。考虑这个相关的答案: