2016-12-14 64 views
0

在我的情況下,企業(公司)可以有幾個網站(filiales),我想獲得格式數組的所有filiales。如何使用n1ql將變量傳遞到子查詢中?

在json企業(公司)中,沒有網站信息(filiales),在json網站(filiales)中,它有企業(公司)uid。 的Json企業公司(公司):

{ 
    "type": "entreprise", 
    "dateUpdate": 1481716305279, 
    "owner": { 
    "type": "user", 
    "uid": "PNnqarPqSdaxmEJ4DoMv-A" 
    } 
} 

Json的網站(分公司):

{ 
    "type": "site", 
    "entreprise": { 
    "uid": "3c0CstzsTjqPdycL5yYzJQ", 
    "type": "entreprise" 
    }, 
    "nom": "test" 
} 

我試着查詢:

SELECT 
      META(entreprise).id as uid, 
      ARRAY s FOR s IN (SELECT d.* FROM default d WHERE d.type = "site" AND d.entreprise.uid = uid) END as sites, 
      entreprise.* 
     FROM default entreprise 
     WHERE entreprise.type = "entreprise"; 

結果:錯誤

{ 
    "code": 5010, 
    "msg": "Error evaluating projection. - cause: FROM in correlated subquery must have USE KEYS clause: FROM default." 
    } 

然後我使用別名:

SELECT 
    META(entreprise).id as uid, 
    ARRAY s FOR s IN (SELECT d.* FROM default d WHERE d.type = "site" AND d.entreprise.uid = META(entreprise).id) END as sites, 
    entreprise.* 
FROM default entreprise 
WHERE entreprise.type = "entreprise"; 

結果:sites數組爲空。

回答

2

首先,你必須對你的站點的文檔創建索引:

CREATE INDEX site_ent_idx ON default(entreprise.uid) WHERE type="site"; 

然後改變你的查詢中使用新的索引:

SELECT 
META(entreprise).id as uid, 
ARRAY s FOR s IN (
    SELECT site.* 
    FROM default as ent USE KEYS META(entreprise).id 
    JOIN default as site ON KEY site.entreprise.uid FOR ent 
) END as sites, 
entreprise.* 
FROM default entreprise 
WHERE entreprise.type = "entreprise" 

這個解決方案應該滿足您的需求。

+0

Merci,它的工作原理。 :) –