在 Microsoft SQL Server 2017 图形数据库中查询可选关系的语法?

Syntax to query for optional relationships in Microsoft SQL Server 2017 Graph Database?

我想 select . Similar to optional in 中的可选关系,例如:

PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name ?mbox
WHERE  { ?x foaf:name  ?name .
     OPTIONAL { ?x  foaf:mbox  ?mbox }
   }

来自 https://www.w3.org/2001/sw/DataAccess/rq23/#OptionalMatching.

LEFT JOIN in normal 相似;例如:

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

通过 MATCH 有更简单的方法吗?

documentation of MATCH describes no 'optional' construct and the remarks状态:

OR and NOT operators are not supported in the MATCH pattern. MATCH can be combined with other expressions using AND in the WHERE clause. However, combining it with other expressions using OR or NOT is not supported.

您可以组合 LEFT JOIN with MATCH. Put the optional MATCH in a separate nested query. Put the optional subquery in a LEFT JOIN-子句。

查询有点繁琐。主要graph search pattern and the optional graph search pattern need separate Node-tables to use the graph MATCH-syntax. A third instance of the Node-table is needed to LEFT JOIN the optional clause on. This third Node-table instance must be separate from the Node-table used to MATCH the main query part on since using MATCH requires1 a table_or_view_name and cannot use a <joined_table>.

OP 示例没有主图搜索模式,因此使用嵌套 JOIN 几乎没有什么好处。但是,这将是结果查询:

SELECT [pLhs].[name],
    [mbox]
FROM [Persons] as [pLhs]
LEFT JOIN (
    SELECT [pRhs].$node_id AS [pRhsNodeId],
        [mbox]
    FROM [Persons] as [pRhs]
        [PersonMailBoxLink],
        [MailBoxes]
    WHERE MATCH ([Persons]-([PersonMailBoxLink])->[MailBoxes])
) AS [optionalGsp] ON [pLhs].$node_id = [optionalGsp].[pRhsNodeId];

一个包含主图搜索模式和可选图搜索模式的更扩展的示例更好地展示了图 MATCH 与可选 LEFT JOIN 的组合。下面使用了SQL Graph Sample Database; select John 的朋友以及这些朋友喜欢的餐厅(可选):

SELECT [Person].[Name] as friend,
    [optionalGsp].[resaurantName],
FROM [Person] AS person1,
    [Person] AS person2,
    [friendOf],
    [Person] AS person2Lhs
    LEFT JOIN (
        SELECT person2Rhs.$node_id AS rhsNodeId,
            [Restaurant].[Name] AS restaurantName
        FROM [Person] AS person2Rhs,
            [likes],
            [Restaurant]
        WHERE MATCH (person2Rhs-(likes)->Restaurant)
    ) AS optionalGsp
WHERE MATCH (person1-(friendOf)->person2)
AND person1.name = 'John'
AND person2.$node_id = person2Lhs.$node_id

原来sample database每个人都喜欢餐厅,所以上面的复杂查询和MATCH(person1-(friendOf)->person2-(likes)->Restaurant)没有区别。然而,当你删除 Sally liking Ginger and Spice:

DELETE FROM likes
WHERE $from_id = (SELECT $node_id FROM Persons WHERE name = 'Sally')
AND $to_id = (SELECT $node_id FROM Restaurants WHERE name = 'Ginger and Spice')

带有可选 LEFT JOIN 的查询仍然 returns Sally 作为 John 的朋友。结果显示 Sally 的餐厅 NULLMATCH(person1-(friendOf)->person2-(likes)->Restaurant) 不显示 Sally。


1 MATCH §Arguments and 描述对可在 MATCH 子句中使用的表格的限制。