请问大佬,这个合并查询结果和单次查询结果为什么不一样??
发布于 5 年前 作者 fgksgf 1925 次浏览 来自 问答

图数据库中的关系如图: Jietu20190307-145649.jpg

我想查询CarC涉及的交通事故中有多少次属于单方事故(即只有一辆车与某事故相关联),以上图为例,CarC的单方事故次数应为6(C1-C6)。

我的想法是:

  1. 先算出CarC涉及的总事故次数total:
match (c1:Car)-[:INVOLVE]-(a1:Accident)
where c1.name = "CarC"
with count(distinct a1) as total
return total

得到 total = 7

  1. 然后算双方事故次数bin:
match(c1:Car)-[:INVOLVE]-(a2:Accident)-[:INVOLVE]-(c2:Car)
where c1.name = "CarC"
with count(distinct a2) as bin
return bin

得到 bin = 1

因此我想使用下面语句将前面两个查询合并

match (c1:Car)-[:INVOLVE]-(a1:Accident), (c1)-[:INVOLVE]-(a2:Accident)-[:INVOLVE]-(c2:Car)
where c1.name = "CarC"
with count(distinct a1) as total, count(distinct a2) as bin
return total,bin

这样得到的结果却是:toatal = 6, bin = 1

请问为什么会不一样?

2 回复

选择表格视图查看下,不要图视图

个人认为这是关系的独特性引起的,即在一个模式中的关系不会是一样的两条关系,即在match (c1:Car)-[:INVOLVE]-(a1:Accident), (c1)-[:INVOLVE]-(a2:Accident)-[:INVOLVE]-(c2:Car)这条语句中,三个没有起名字的类型为Involve的关系,是不能够相同的。详见官方文档:https://neo4j.com/docs/cypher-manual/current/introduction/uniqueness/

回到顶部