N1QL(Couchbase) - 对于不存在的关系,在couchbase中进行真正的LEFT JOIN

时间:2017-12-19 09:22:30

标签: couchbase n1ql

为简单起见,我们假设我有以下数据库:

{
    id: "a_id",   // This is the key, not a field in the document
    type: "a"
}
{
    id: "b_id",
    type: "b",
    a: "a_id"
}
{
     type: "c",
     b: "b_id"
}

正如你所看到的,有一种经典的亲子关系(" a"有很多" b"," b"有很多" C&#34) 让我们假设不会总是存在类型" c"文件 - 例如,我有五个" b"文件,但只有一个有" c"与之相关的文件。 我想写一个JOIN查询,它会给我所有" b"属于" a",如果它们存在 - 所有" c"属于" b"但是对于" b"没有" c"我没有得到任何结果 - 我想得到所有五个" b"文件,以及一个" c"相关的文件。 我的查询如下:

SELECT *
FROM default AS a
JOIN default AS b ON KEY b.a FOR a
JOIN default AS c ON KEY c.b FOR b
WHERE a.type = "a"
AND b.type = "b"
AND c.type = "c";

我在这里缺少什么? 谢谢!

1 个答案:

答案 0 :(得分:1)

WHERE子句post join过滤器,如果c为MISSING,则c.type =“c”为false。

INSERT INTO default VALUES("a_id", { "type": "a" });
INSERT INTO default VALUES("b_id", { "type": "b", "a":"a_id"});
INSERT INTO default VALUES("b_id1", { "type": "b", "a":"a_id"});
INSERT INTO default VALUES("b_id1", { "type": "b", "a":"a_id"});
INSERT INTO default VALUES("b_id2", { "type": "b", "a":"a_id"});
INSERT INTO default VALUES("b_id3", { "type": "b", "a":"a_id"});
INSERT INTO default VALUES("b_id4", { "type": "b", "a":"a_id"});
INSERT INTO default VALUES("c_id", { "type": "c", "b":"b_id"});

CREATE INDEX ia ON default(a);
CREATE INDEX ib ON default(b);

SELECT *
FROM default AS d
LEFT JOIN default AS d1 ON KEY d1.a FOR d
LEFT JOIN default AS d2 ON KEY d2.b FOR d1
WHERE d.type = "a"
AND d1.type = "b"
AND (d2 IS MISSING OR d2.type = "c");

同时结帐https://dzone.com/articles/visually-explaining-n1ql-joins