select中的regexp_matches查询返回空结果集

时间:2016-09-27 16:39:45

标签: sql postgresql postgresql-9.4

我有以下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;

表中有以下记录:

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

查询结果为:

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

然后我更换了字符串' 24'通过'项目'在查询中,我期待这个结果:

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

但结果是:

Empty result set

如果函数regexp_matches不匹配,则函数regexp_matches可能不返回任何行。

如何修复查询,以便即使regexp_matches不匹配也会返回行?

提前致谢。

1 个答案:

答案 0 :(得分:1)

regexp_matches会返回一个setof text[],即一张表,而且有时会将其用作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数组。