Neo4j 找到所有匹配 X 但不匹配 Y

Neo4j find all that match X but don't match Y

我有一个简单的学生和课程域。一个学生可以注册多门课程。

我想找到所有注册了课程 1234 而没有注册课程 5678 的学生

所以我尝试了这个尝试:

MATCH (s:Student)
MATCH (c:Course)
MATCH (s)-[r:REGISTRATION]->(c {code: "1234"})
WHERE NOT (s)-[r:REGISTRATION]->(c {code: "5678"})
RETURN s

但是最后的WHERE NOT好像对查询没有影响?我仍然可以从查询结果中找到也注册了第二门课程的学生:/

我做错了什么?

你可以这样做:

MATCH (sUnwnated:Student)-[r:REGISTRATION]->(:Course{code: "5678"}) // get all students in "5678"
WITH COLLECT(sUnwnated) AS sUnwnated // group them to a list                
MATCH (sWanted:Student)-[r:REGISTRATION]->(:Course{code: "1234"}) // get all students in "1234"
WHERE NOT sWanted IN sUnwnated // but keep only these that are not in the list
RETURN sWanted

显然,我只遗漏了一个重要的 keyword/function、exists()

这个有效:

MATCH (s:Student)
MATCH (c:Course)
MATCH (s)-[r:REGISTRATION]->(c {code: "1234"})
WHERE NOT exists((s)-[r:REGISTRATION]->(c {code: "5678"}))
RETURN s