I want to select optional relationships in sql-server-2017-graph. Similar to optional in sparql e.g.:
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name ?mbox
WHERE { ?x foaf:name ?name .
OPTIONAL { ?x foaf:mbox ?mbox }
}
from https://www.w3.org/2001/sw/DataAccess/rq23/#OptionalMatching.
And similar to LEFT JOIN in normal sql; e.g.:
SELECT name, mbox
FROM Persons
LEFT JOIN PersonMailBoxLink ON Persons.$node_id = PersonMailBoxLink.$from_id
LEFT JOIN MailBoxes ON PersonMailBoxLink.$to_id = MailBoxes.$node_id
Is there an easier way via MATCH?
The documentation of MATCH describes no 'optional' construct and the remarks state:
ORandNOToperators are not supported in theMATCHpattern.MATCHcan be combined with other expressions usingANDin theWHEREclause. However, combining it with other expressions usingORorNOTis not supported.
You can combine
LEFT JOINwithMATCH. Put the optionalMATCHin a separate nested query. Put the optional subquery in aLEFT JOIN-clause.The query is a bit cumbersome. The main graph search pattern and the optional graph search pattern need separate
Node-tables to use the graphMATCH-syntax. A third instance of theNode-table is needed toLEFT JOINthe optional clause on. This thirdNode-table instance must be separate from theNode-table used toMATCHthe main query part on since usingMATCHrequires1 atable_or_view_nameand cannot use a<joined_table>.The OP example has no main graph search pattern, so there is little benefit from using a nested
JOIN. However, this would be the resulting query:A more extended example with both a main graph search pattern and an optional graph search pattern give a better demonstration of combing graph
MATCHwith optionalLEFT JOIN. The following uses the SQL Graph Sample Database; select John's friends and optionally the restaurants that these friends like:In the original sample database every person likes a restaurant, so the is no difference between the complicate query above and
MATCH(person1-(friendOf)->person2-(likes)->Restaurant). However, when you delete Sally liking Ginger and Spice:The query with the optional
LEFT JOINstill returns Sally as a friend ofJohn. The results showNULLfor Sally's restaurant.MATCH(person1-(friendOf)->person2-(likes)->Restaurant)does not show Sally.1
MATCH§Arguments and Use views and table valued functions as node or edge tables in match clauses describe this restriction on the tables that can be used in theMATCH-clause.