跳转至

CASE表达式Graph

CASE表达式使用条件来过滤nGQL查询语句的结果,常用于YIELDRETURN子句中。和openCypher一样,nGQL提供两种形式的CASE表达式:简单形式和通用形式。

CASE表达式会遍历所有条件,并在满足第一个条件时停止读取后续条件,然后返回结果。如果不满足任何条件,将通过ELSE子句返回结果。如果没有ELSE子句且不满足任何条件,则返回NULL

简单形式Graph

语法Graph

CASE <comparer>
WHEN <value> THEN <result>
[WHEN ...]
[ELSE <default>]
END

Caution

CASE表达式一定要用END结尾。

参数 说明
comparer 用于与value进行比较的值或者有效表达式。
value comparer进行比较,如果匹配,则满足此条件。
result 如果value匹配comparer,则返回该result
default 如果没有条件匹配,则返回该default

示例Graph

nebula> RETURN \
        CASE 2+3 \
        WHEN 4 THEN 0 \
        WHEN 5 THEN 1 \
        ELSE -1 \
        END \
        AS result;
+--------+
| result |
+--------+
| 1      |
+--------+
nebula> GO FROM "player100" OVER follow \
        YIELD properties($$).name AS Name, \
        CASE properties($$).age > 35 \
        WHEN true THEN "Yes" \
        WHEN false THEN "No" \
        ELSE "Nah" \
        END \
        AS Age_above_35;
+-----------------+--------------+
| Name            | Age_above_35 |
+-----------------+--------------+
| "Tony Parker"   | "Yes"        |
| "Manu Ginobili" | "Yes"        |
+-----------------+--------------+

通用形式Graph

语法Graph

CASE
WHEN <condition> THEN <result>
[WHEN ...]
[ELSE <default>]
END
参数 说明
condition 如果条件condition为true,表示满足此条件。
result condition为true,则返回此result
default 如果没有条件匹配,则返回该default

示例Graph

nebula> YIELD \
        CASE WHEN 4 > 5 THEN 0 \
        WHEN 3+4==7 THEN 1 \
        ELSE 2 \
        END \
        AS result;
+--------+
| result |
+--------+
| 1      |
+--------+
nebula> MATCH (v:player) WHERE v.age > 30 \
        RETURN v.name AS Name,  \
        CASE \
        WHEN v.name STARTS WITH "T" THEN "Yes" \
        ELSE "No" \
        END \
        AS Starts_with_T;
+---------------------+---------------+
| Name                | Starts_with_T |
+---------------------+---------------+
| "Tim"               | "Yes"         |
| "LaMarcus Aldridge" | "No"          |
| "Tony Parker"       | "Yes"         |
+---------------------+---------------+

简单形式和通用形式的区别Graph

为了避免误用简单形式和通用形式,用户需要了解它们的差异。请参见如下示例:

nebula> GO FROM "player100" OVER follow \
        YIELD properties($$).name AS Name, properties($$).age AS Age, \
        CASE properties($$).age \
        WHEN properties($$).age > 35 THEN "Yes" \
        ELSE "No" \
        END \
        AS Age_above_35;
+-----------------+-----+--------------+
| Name            | Age | Age_above_35 |
+-----------------+-----+--------------+
| "Tony Parker"   | 36  | "No"         |
| "Manu Ginobili" | 41  | "No"         |
+-----------------+-----+--------------+

示例本意为当玩家年龄大于35时输出Yes。但是查看输出结果,年龄为36时输出的却是No

这是因为查询使用了简单形式的CASE表达式,比较对象是$$.player.age$$.player.age > 35。当年龄为36时:

  • $$.player.age的值为36,数据类型为int。
  • $$.player.age > 35的值为true,数据类型为boolean。

这两种数据类型无法匹配,不满足条件,因此返回No


最后更新: November 1, 2021
Back to top