每个特定类型文档的 N1QL 查询计数
N1QL query count for each document of specific type
我是 couchbase 和非关系数据库的新手。
我有一个包含球员和球队的桶(2 种类型的文件)。
每个球员都有类型,playedFor(一个包含他参加过的所有球队的数组)和一个名字,例如:
{
"type":"player"
"name":"player1"
"playedFor": [
"England/Manchester/United"
"England/Manchester/City"
]
}
每个团队都有类型、名称和类别,例如:
{
"type": "team"
"name": "England/Manchester/City"
"category": "FC"
}
我想知道每个类别 FC 的球队有多少球员上场。
我做了这个查询来为特定团队计算:
SELECT COUNT(1) AS total
FROM bucket AS a
WHERE a.type='player'
AND (any r in a.playedFor satisfies r in ["England/Manchester/United"] end)
但是我如何为所有团队进行此查询?
您为该数据建模的方式存在问题,即玩家可以为 1 支或多支球队效力(因此为数组)。
解决这个问题的一种方法是使用 Couchbase 的 UNNEST clause 来“展平”这些数组(它基本上是将文档连接到数组中的每个项目)。
到那时,它变得和标准一样简单 GROUP BY
。这是一个例子:
SELECT team, count(1) AS totalPlayers
FROM `bucket` AS a
UNNEST a.playedFor team
WHERE a.type='player'
GROUP BY team
此查询将生成如下输出:
[
{
"team": "Pittsburgh/Pirates",
"totalPlayers": 8
},
{
"team": "England/Manchester/United",
"totalPlayers": 10
},
{
"team": "England/Manchester/City",
"totalPlayers": 15
},
{
"team": "Cincinnati/Reds",
"totalPlayers": 21
}
]
(抱歉,我用 MLB 球队来扩充你的样本,因为我对足球队了解不多)。
请注意,单独的团队文档并未计入此查询,但如果您的查询需要他们的信息,您也可以 JOIN
给他们。
我是 couchbase 和非关系数据库的新手。
我有一个包含球员和球队的桶(2 种类型的文件)。 每个球员都有类型,playedFor(一个包含他参加过的所有球队的数组)和一个名字,例如:
{
"type":"player"
"name":"player1"
"playedFor": [
"England/Manchester/United"
"England/Manchester/City"
]
}
每个团队都有类型、名称和类别,例如:
{
"type": "team"
"name": "England/Manchester/City"
"category": "FC"
}
我想知道每个类别 FC 的球队有多少球员上场。 我做了这个查询来为特定团队计算:
SELECT COUNT(1) AS total
FROM bucket AS a
WHERE a.type='player'
AND (any r in a.playedFor satisfies r in ["England/Manchester/United"] end)
但是我如何为所有团队进行此查询?
您为该数据建模的方式存在问题,即玩家可以为 1 支或多支球队效力(因此为数组)。
解决这个问题的一种方法是使用 Couchbase 的 UNNEST clause 来“展平”这些数组(它基本上是将文档连接到数组中的每个项目)。
到那时,它变得和标准一样简单 GROUP BY
。这是一个例子:
SELECT team, count(1) AS totalPlayers
FROM `bucket` AS a
UNNEST a.playedFor team
WHERE a.type='player'
GROUP BY team
此查询将生成如下输出:
[
{
"team": "Pittsburgh/Pirates",
"totalPlayers": 8
},
{
"team": "England/Manchester/United",
"totalPlayers": 10
},
{
"team": "England/Manchester/City",
"totalPlayers": 15
},
{
"team": "Cincinnati/Reds",
"totalPlayers": 21
}
]
(抱歉,我用 MLB 球队来扩充你的样本,因为我对足球队了解不多)。
请注意,单独的团队文档并未计入此查询,但如果您的查询需要他们的信息,您也可以 JOIN
给他们。