【问题标题】:Postgres query to calculate matching strings用于计算匹配字符串的 Postgres 查询
【发布时间】:2016-11-01 02:01:17
【问题描述】:

我有下表:

id   description additional_info
123    XYZ          XYD

还有一个数组:

[{It is known to be XYZ},{It is know to be none},{It is know to be XYD}]

我需要以这样一种方式映射这两个内容,即对于表的每条记录,我都能够定义成功匹配的数量。 上述示例的结果将是:

id    RID    Matches
1     123    2

只有位置 0 和 2 的内容与记录的 description/additional_info 匹配,所以 Matches 在结果中是 2。

我正在努力将其转换为 Postgres 中的查询 - 准确地说是动态 SQL 在 PL/pgSQL 函数中创建 VIEW

【问题讨论】:

    标签: sql ruby-on-rails postgresql plpgsql dynamic-sql


    【解决方案1】:

    未定义如何处理同时匹配 both descriptionadditional_info 的数组元素。我假设您想将其计为 1 场比赛。

    id = 1 在结果中的来源也未定义。

    一种方法是将unnest() 数组和LEFT JOIN 主表的每个元素放在两列中的任意一个上进行匹配:

    SELECT 1 AS id, t.id AS "RID", count(a.txt) AS "Matches"
    FROM   tbl t
    LEFT   JOIN unnest(my_arr) AS a(txt) ON a.txt ~ t.description
                                         OR a.txt ~ t.additional_info
    GROUP  BY t.id;
    

    我使用正则表达式进行匹配。右侧字符串中的 (.\?) 等特殊字符具有特殊含义。如果可能的话,你可能不得不逃避那些。


    Addressing your comment

    您应该提到您正在使用带有EXECUTE 的plpgsql 函数。可能有 2 个错误:

    1. 变量array_contentEXECUTE 中不可见,您需要使用USING 子句传递值 - 或在不允许参数的CREATE VIEW 语句中将其连接为字符串文字。

    2. 字符串'brand_relevance_calculation_‌​view' 周围缺少单引号。在您将其连接为标识符之前,它仍然是一个字符串文字。你在 %I 那里使用 format() 做得很好。

    演示:

    DO
    $do$
    DECLARE
       array_content varchar[]:= '{FREE,DAY}'; 
    BEGIN
    
    EXECUTE format('
       CREATE VIEW %I AS
       SELECT id, description, additional_info, name, count(a.text) AS business_objectives
            , multi_city, category IS NOT NULL AS category
       FROM initial_events i
       LEFT JOIN unnest(%L::varchar[]) AS a(text) ON a.text ~ i.description
                                                  OR a.text ~ i.additional_info'
     , 'brand_relevance_calculation_‌​view', array_content);
    
    END
    $do$;
    

    【讨论】:

    • 我使用的查询是:EXECUTE format('CREATE VIEW %I AS SELECT id ,description, additional_info, name, count(a.text) business_objectives, multi_city, category is not null as category FROM initial_events LEFT JOIN unnest(array_content) AS a(text) ON a.text ~ initial_events.description OR a.text ~ initial_events.additional_info',brand_relevance_calculation_view);但是它抛出了一个异常,即列“array_content”不存在,尽管我将其定义为:array_content varchar[]:= ARRAY['FREE','DAY'];
    • 显示无效的正则表达式。当我查询创建的 sql 视图时,括号不平衡。
    • @himanshu:就像我提到的:Special characters like (.\?) etc. in the strings to the right have special meaning. You might have to escape those if possible. 或使用LIKE 代替:('%' || a.text || '%') LIKE i.description 等 - 只有 %_\\ 有特殊含义。或者,如果您只想在示例中的字符串末尾匹配:('%' || a.text) LIKE i.description,
    • @himanshu:请为新问题开始一个新问题。您可以随时链接到这个以获取上下文。
    猜你喜欢
    • 2021-02-15
    • 2016-07-19
    • 2014-04-20
    • 2011-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-03
    • 2019-09-20
    相关资源
    最近更新 更多