天天看點

Neo4j Cypher CASE語句

在Cypher的文法中常見的CASE語句有兩種:

Simple CASE form

Generic CASE form

。官方給的解釋是:

Simple CASE form: comparing an expression against multiple values;

Generic CASE form: allowing for multiple conditionals to be expressed;

CASE語句的作用是:如果滿足條件語句中的條件,則傳回此條件的結果;否則傳回

ELSE

的結果;如果CASE語句中沒有

ELSE

,則傳回

null

換句話說,CASE語句與程式設計語言中的

IF...ELSE..

語句類似

**

Simple CASE form

**

syntax

CASE test
    WHEN value THEN result
    [WHEN ...]
    [ELSE default]
END
           

Arguments

Name Description
test A valid expression
value An expression whose result will compared to test
result This is the expression returned as output if value matches test
default if not match is found, default is returned

For Example

MATCH (n)
RETURN
CASE n.eyes
WHEN 'blue'
THEN 1
WHEN 'brown'
THEN 2
ELSE 3 END AS result
           

**

Generic CASE form

**

syntax

CASE
WHEN predicate THEN result
    [WHEN ...]
    [ELSE default]
END
           

Arguments

name Description
predicate A predicate that is tested to find a valid alternative.
result This is the expression returned as output if predicate evaluates to true.
default if no match is found, default is returned.

For Example

MATCH (n)
RETURN
CASE
WHEN n.eyes == 'blue'
THEN 1
WHEN n.age < 40
THEN 2
ELSE 3 END AS result
           

**

區分何時使用Generic CASE form,何時使用Simple CASE form

**

問題:

假如,我們需要輸出所有使用者10年前的年齡,如果年齡屬性為空,則輸出-1,否則輸出年齡age-10

Simple CASE

MATCH (n)
RETURN n.name,
CASE n.age
WHEN n.age IS NULL THEN -1
ELSE n.age - 10 END AS age_10_years_ago
           

如果采用此種方法,

WHEN n.age IS NULL THEN -1

條件語句将永遠不會被執行。因為

n.age

Integer

類型,而

n.age is NULL

是布爾類型。是以會執行

ELSE n.age - 10 END AS age_10_years_ago

,傳回

null

Generic CASE

MATCH (n)
RETURN n.name,
CASE
WHEN n.age IS NULL THEN -1
ELSE n.age - 10 END AS age_10_years_ago
           

将傳回正确的結果

繼續閱讀