匹配列值并忽略 PostgreSQL 11.0 中的特殊字符

Match column values and ignoring special characters in PostgreSQL 11.0

我在 PostgreSQL 11.0

中关注 table
name                                            identifier  name_matched
anti-angin® formula                             3792673     anti angin
anti-angin® formula                             3792673     anti angin
arava® 20 mg tablets                            D25155      arava 20 mg
nifedipine extended release tablets 60 mg       23766       nifedipine

我使用以下查询来匹配名称和 name_matched 值。

select * from tbl
where name ilike '%' || name_matched || '%' 

以上查询仅给出第 4 行作为输出。如何修改查询以获取所有四行(忽略特殊字符然后匹配字符串)

非常感谢任何帮助

这应该适用于示例数据中显示的值组合。鉴于您需要处理 - 个字符,您可能还需要处理其他情况。如果出现任何问题,请发表评论,我会看看是否可以帮助您解决这些问题。

select *
  from tbl
 where replace(regexp_replace(name, '[^A-Za-z0-9 -]', ''), '-', ' ') ~*
       replace(regexp_replace(name_matched, '[^A-Za-z0-9 -]', ''), '-', ' ')
;

select * from tbl
where
  array(select x[1] from regexp_matches(name_matched, '([a-zA-Z0-9]+)', 'g') as x) <@
  array(select x[1] from regexp_matches(name, '([a-zA-Z0-9]+)', 'g') as x);

或缩短:

create function regexp_matches_array(astr text, apattern text)
  returns text[]
  language sql
  immutable
  strict
as $func$
  select array_agg(x[1]) from regexp_matches(astr, apattern, 'g') as x
$func$

select * from tbl
where
  regexp_matches_array(name_matched, '([a-zA-Z0-9]+)') <@
  regexp_matches_array(name, '([a-zA-Z0-9]+)');

请注意,它没有考虑单词顺序。