在内联数组上使用postgresql模糊运算符

时间:2014-11-25 15:19:45

标签: postgresql

我想在不是来自表格的数据上利用postgresql模糊匹配,最终目标是尝试将国家/地区名称与拼写错误匹配。我试过这个:

select foo from (select ARRAY['France', 'Thailand', 'Germany' ]) as foo where 'Thailande' % any(foo);

产生错误:

ERROR:  op ANY/ALL (array) requires array on right side

尝试类型转换foo似乎意味着我的子选择语句的结果不被视为类型数组而是​​记录:

=> select foo from (select ARRAY['France', 'Thailand', 'Germany' ]) as foo where 'Thailande' % any(foo::varchar[]);
ERROR:  cannot cast type record to character varying[]
LINE 1: ...', 'Germany' ]) as foo where 'Thailande' % any(foo::varchar[...
                                                             ^

是否有任何意图强制数组类型或以其他方式完成所需的结果?

注意:我正在使用postgresql-9.3.5

1 个答案:

答案 0 :(得分:1)

我认为这里的重点是foo不指定字段而是指定行。

可能你想要这个:

select foo from (select ARRAY['France', 'Thailand', 'Germany' ]) as a(foo)
  where 'Thailande' % any(a.foo);

但请注意,这将选择整个数组,而不是匹配Thailande的单个组件。

要获得单词,我不是首先使用数组而是使用VALUES子句,如:

select foo from (values ('France'), ('Thailand'), ('Germany')) 
 as a(foo)
where 'Thailande' % a.foo;

结果:

   foo    
----------
 Thailand