在 select returns 空结果集中使用 regexp_matches 进行查询

Query with regexp_matches in select returns empty result set

我关注SQL:

SELECT code, name
ARRAY_TO_JSON(regexp_matches(code, '^(.*?)(24)(.*)$','i')) AS match_code,
ARRAY_TO_JSON(regexp_matches(name, '^(.*?)(24)(.*)$','i')) AS match_name
FROM manufacturer
WHERE (code  ~* '^(.*?)(24)(.*)$' OR name  ~* '^(.*?)(24)(.*)$')
ORDER BY name;

table中有如下记录:

code | name
-------------
24   | Item 24

查询结果为:

code | name    | match_code   | match_name
-------------------------------------------------
24   | Item 24 | ["","24",""] | ["Item ","24",""]

然后我在查询中用 'Item' 替换了字符串 '24',我希望得到这样的结果:

code | name    | match_code   | match_name
-------------------------------------------------
24   | Item 24 | []           | ["", "Item ","24"]

但结果是:

Empty result set

函数regexp_matches可能returns如果不匹配则没有行。

如何修复查询,使其 returns 行即使 regexp_matches 不匹配?

提前致谢。

regexp_matches returns a setof text[],即 table,有时将其用作 SELECT 中的输出表达式会造成混淆。您可以创建子查询,以便将其移动到 FROM 子句。试试这个:

SELECT
    code,
    name,
    coalesce(array_to_json((SELECT * FROM regexp_matches(code, '^(.*?)(24)(.*)$','i'))),'[]') AS match_code,
    coalesce(array_to_json((SELECT * FROM regexp_matches(name, '^(.*?)(24)(.*)$','i'))),'[]') AS match_name
FROM manufacturer
WHERE (code  ~* '^(.*?)(24)(.*)$' OR name  ~* '^(.*?)(24)(.*)$')
ORDER BY name;

请注意,我还使用 coalesceNULL(如果没有匹配项,这是我们从 regexp_matches 子查询中获得的)转换为空的 JSON数组。