SQL图数据库中SHORTEST_PATH与EXISTS结合查询时多部分标识符无法绑定的问题
Let's break down why you're hitting this error and how to fix it.
The Root Cause
In your query, the Person table in the FROM clause acts as the starting node for your SHORTEST_PATH pattern. When using SHORTEST_PATH with FOR PATH aliases for path elements, SQL Server treats unaliased starting nodes as part of the path's node collection rather than a single, discrete row. This is why referencing Person.ID in the EXISTS clause throws the "multi-part identifier could not be bound" error—SQL can't resolve which specific row's ID you're referring to.
Solution 1: Alias the Starting Node
Give your starting Person node a clear alias, then use that alias in the EXISTS clause. This tells SQL Server to reference the single starting row instead of the path collection:
SELECT * FROM Person AS StartPerson, friendOf FOR PATH, Person FOR PATH as Person2 WHERE MATCH (SHORTEST_PATH(StartPerson(-(friendOf)->Person2)+)) AND EXISTS (SELECT * FROM Person p3 WHERE p3.ID = StartPerson.ID)
(Note: Your example EXISTS clause is redundant here since StartPerson is already a row from Person, but this pattern works seamlessly for real-world conditions like filtering based on related data in other tables.)
Solution 2: Embed Filters Directly in the MATCH Clause
If your goal is to filter starting nodes, you can integrate the condition directly into the MATCH pattern using a WHERE clause on the starting node. This is often more efficient for SQL Graph queries:
SELECT * FROM Person, friendOf FOR PATH, Person FOR PATH as Person2 WHERE MATCH (SHORTEST_PATH( Person WHERE EXISTS (SELECT * FROM Person p3 WHERE p3.ID = Person.ID) -(friendOf)->Person2)+)
Key Takeaway
When working with SHORTEST_PATH, always alias your starting node if you need to reference its properties outside the MATCH clause. This eliminates ambiguity between the starting row and the collection of nodes in the generated path.
内容的提问来源于stack exchange,提问作者Tony Thomas

