用于计算匹配字符串的 Postgres 查询
Postgres query to calculate matching strings
我关注table:
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}]
我需要以这样一种方式映射这两个内容,即对于 table 的每条记录,我都能够定义成功匹配的数量。
上述示例的结果将是:
id RID Matches
1 123 2
只有位置0和位置2的内容匹配记录的description
/additional_info
所以结果Matches
是2。
我正在努力将其转换为 Postgres 中的查询 - 动态 SQL 准确地说是在 PL/pgSQL 函数中创建 VIEW
。
未定义如何处理同时匹配description
和additional_info
的数组元素。我假设您想将其计为 1 场比赛。
结果中 id = 1
的来源也是未定义的。
一种方法是 unnest()
数组和 LEFT JOIN
主 table 匹配两列中任一列的每个元素:
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;
我使用正则表达式进行匹配。右边字符串中的(.\?
)等特殊字符具有特殊含义。如果可能的话,你可能不得不逃避那些。
您应该提到您正在使用带有 EXECUTE
的 plpgsql 函数。可能有 2 个错误:
变量 array_content
在 EXECUTE
中不可见,您需要使用 USING
子句传递值 - 或者将其连接为字符串文字CREATE VIEW
不允许参数的语句。
字符串 'brand_relevance_calculation_view'
周围缺少单引号。在将它连接为标识符之前,它仍然是一个字符串文字。你很好地使用了 format()
和 %I
。
演示:
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$;
我关注table:
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}]
我需要以这样一种方式映射这两个内容,即对于 table 的每条记录,我都能够定义成功匹配的数量。 上述示例的结果将是:
id RID Matches
1 123 2
只有位置0和位置2的内容匹配记录的description
/additional_info
所以结果Matches
是2。
我正在努力将其转换为 Postgres 中的查询 - 动态 SQL 准确地说是在 PL/pgSQL 函数中创建 VIEW
。
未定义如何处理同时匹配description
和additional_info
的数组元素。我假设您想将其计为 1 场比赛。
结果中 id = 1
的来源也是未定义的。
一种方法是 unnest()
数组和 LEFT JOIN
主 table 匹配两列中任一列的每个元素:
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;
我使用正则表达式进行匹配。右边字符串中的(.\?
)等特殊字符具有特殊含义。如果可能的话,你可能不得不逃避那些。
您应该提到您正在使用带有 EXECUTE
的 plpgsql 函数。可能有 2 个错误:
变量
array_content
在EXECUTE
中不可见,您需要使用USING
子句传递值 - 或者将其连接为字符串文字CREATE VIEW
不允许参数的语句。字符串
'brand_relevance_calculation_view'
周围缺少单引号。在将它连接为标识符之前,它仍然是一个字符串文字。你很好地使用了format()
和%I
。
演示:
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$;