如何在N1QL couchbase中进行LEFT JOIN?

时间:2017-08-11 14:49:14

标签: sql database couchbase n1ql

我正在尝试在couchbase中对表进行简单的LEFT JOIN。这就是我所拥有的:

SELECT
  a.*,
  b.id,
  b.name
  FROM my_table AS a LEFT JOIN my_table AS b
  ON KEYS a.pid
  WHERE a.id='abc'

但由于某种原因,我得到的结果不包括右侧表格的字段。任何人都可以帮助我实现类似于我们在关系数据库SQL中可以做的事情,如下所示?

SELECT
  a.*,
  b.id,
  b.name
  FROM my_table AS a LEFT JOIN my_table AS b
  ON a.pid=b.id
  WHERE a.id='abc'

谢谢!

1 个答案:

答案 0 :(得分:0)

如果没有匹配的JOIN右侧投影为(NOSQL)JSON中的MISSING与SQL中的NULL(即它将LEFT侧文档右侧延伸为MISSING)

SELECT
  a.*,
  (CASE WHEN b IS MISSING THEN NULL ELSE b.id END) AS id,
  (CASE WHEN b IS MISSING THEN NULL ELSE b.name END) AS name
  FROM my_table AS a LEFT JOIN my_table AS b
  ON KEYS a.pid
  WHERE a.id='abc';

如果文档b匹配且b.name为MISSING,您仍然会丢失。如果你需要null,试试这个。

SELECT
  a.*,
  (CASE WHEN b.id IS MISSING THEN NULL ELSE b.id END) AS id,
  (CASE WHEN b.name IS MISSING THEN NULL ELSE b.name END) AS name
  FROM my_table AS a LEFT JOIN my_table AS b
  ON KEYS a.pid
  WHERE a.id='abc';

SELECT
 a.*, 
 IFMISSING(b.id,NULL) AS id, 
 IFMISSING(b.name,NULL) AS name 
 FROM my_table AS a LEFT JOIN my_table AS b 
 ON KEYS a.pid 
 WHERE a.id='abc';