首页 > 解决方案 > 基于文本列的正则表达式模式匹配将表拆分为相关表

问题描述

假设我们有一个产品表,其中每个供应商对同一产品的名称略有不同。使用正则表达式模式匹配来识别我们的相似字符串来拆分表的最佳方法是什么。

请参见以下示例:

p_id     p_name            cat           start_time     vendor              attrs
-------------------------------------------------------------------------------------------
1     'iphone'            'phones'      some date       'google'        some_jsonb
2     'apple iphone'      'phones'      some date       'ebay'           some_other_jsonb

想要的结果:

table A
p_id    p_name 
1      'iphone'

table B
e_id    p_ref    vendor            attrs
1        1      'google'     some_jsonb
2        1      'ebay'       some_other_jsonb

我的问题不在于正则表达式规则或将表拆分为两个相关表,而是在何处以及如何实施我的正则表达式规则以查找列 p_name 中的重复项?

标签: sqlpostgresql

解决方案


如果对于 each p_name,您想要表中已有的最短子名,那么您可以使用如下逻辑:

select e.p_name
from example e
where not exists (select 1
                  from example e2
                  where e.p_name like '%' || e2.p_name || '%' and
                        e.p_name <> e2.pname
                 );

推荐阅读