3

I want to select optional relationships in . Similar to optional in 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 ; 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:

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.

4

1 回答 1

2

你可以LEFT JOIN结合MATCH. 将可选项MATCH放在单独的嵌套查询中。将可选子查询放在 - 子句中LEFT JOIN

查询有点麻烦。主图搜索模式和可选图搜索模式需要单独Node的 -tables 才能使用 graph MATCH-syntax。-table的第三个实例Node需要LEFT JOIN在可选子句上。这第三个-table 实例必须与用于主查询部分Node的 -table 分开,因为 using需要1 a而不能使用 a 。NodeMATCHMATCHtable_or_view_name<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];

一个包含主图搜索模式和可选图搜索模式的更扩展示例更好地演示了将 graphMATCH与 optional结合使用LEFT JOIN。下面使用SQL Graph Sample Database;选择 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

在原始示例数据库中,每个人都喜欢一家餐馆,所以上面的复杂查询和MATCH(person1-(friendOf)->person2-(likes)->Restaurant). 但是,当您删除 Sally 喜欢 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仍然返回 Sally 作为 的朋友John。结果显示NULL为 Sally 的餐厅。 MATCH(person1-(friendOf)->person2-(likes)->Restaurant)没有显示莎莉。


1 MATCH§Arguments and Use views and table valued functions as node or edge tables in match子句描述了对可以在-子句中使用的表的限制MATCH

于 2017-08-24T08:13:17.953 回答