我是Couchbase DB服务器的新手,我试图通过一个查询来实现我对三个查询所做的工作,因为这样做效率不高。
我在同一存储桶中有三种不同的文档类型(x,y,z);都具有类似的键:“区”,像这样:
文档x:
{
"type": "x",
"district": "Some district"
}
文档y:
{
"type": "y",
"district": "Some district"
}
文档z:
{
"type": "z",
"district": "Some district"
}
我目前已经在PHP中实现了以下伪代码:
$totalDistrictInX = "SELECT COUNT(x) FROM bucket WHERE type = 'x' AND district = 'Maboro';
$totalDistrictInY = "SELECT COUNT(x) FROM bucket WHERE type = 'y' AND district = 'Maboro';
$totalDistrictInZ = "SELECT COUNT(x) FROM bucket WHERE type = 'z' AND district = 'Maboro';
$totalCountOfMaboro = $totalDistrictInX + $totalDistrictInY + $totalDistrictInZ;
我无法使用JOIN查询,因为当前使用的Couchbase服务器低于5.50 which only supports joining documents between document key to document field and not between document fields。
是否有一种方法可以通过一个n1ql查询来实现?请提供任何帮助。
答案 0 :(得分:0)
可以使用GROUP BY
和COUNT
组合来解决吗?
SELECT COUNT(x) FROM bucket WHERE district = 'Maboro' GROUP BY type
答案 1 :(得分:0)
使用不带分组依据的汇总查询来计算总数,控制要通过谓词计数的文档。
SELECT COUNT(1) AS cnt
FROM bucket
WHERE type IN ['x', 'y', 'z'] AND district = 'Maboro';
如果每种类型都需要计数,请使用GROUP BY
SELECT type, COUNT(1) AS cnt
FROM bucket
WHERE type IN ['x', 'y', 'z'] AND district = 'Maboro'
GROUP BY type;
如果要计算总数和单个类型,则将其计为数组
SELECT ARRAY_SUM(av[*].cnt) AS totalcnt, av AS details
LET av = (SELECT type, COUNT(1) AS cnt
FROM bucket
WHERE type IN ['x', 'y', 'z'] AND district = 'Maboro'
GROUP BY type);