【发布时间】:2019-10-12 19:21:42
【问题描述】:
问题
我在编写函数式查询计数结果行时遇到了麻烦。
数据库表
我有以下(简化的)表(正在开发的环境是 Drupal 8 btw,使用数据库服务):
nodes 表:
id - 数字 idtitle - varchar
示例条目:
id title
1 My first article
2 My second article
3 My third article
comments 表:
cid - 数字 identity_type - varchar,评论实体entity_id - 数字 id,包含引用status - 整数,0 表示未发布,1 表示已发布comment - 文字
示例条目:
cid entity_type entity_id status comment
1 node 1 1 foo
2 node 1 1 bar
3 comment 1 1 baz
4 node 1 0 spam/foul language/whatever
5 node 2 1 yeeeha
数据结构说明
“节点”可以被注释。 cmets 然后被存储在“cmets”表中。对于每条评论,都有一个专门的行,其中包含评论的 id、评论的实体类型(可以是“节点”和“评论”)以及评论实体的 id。并且 cmets 也可以被评论 - 这些“回复”也被存储在“cmets”表中,因此这些条目包含“评论”作为 entity_id 和回复的评论的 id。
我现在想通过单个查询获得以下结果:
id title comments
1 My first article 3
2 My second article 1
3 My third article 0
comments 应包含所有已发布的 cmets 和对给定节点的已发布回复的总和。因此,如果一个节点被直接评论了两次,并且其中一个 cmets 也被评论了,那么 comments 计数应该声明 3。 (注:atm“回复”到cmets无法回复,所以这里只有3级环境(nodecommentcomment)。
正在使用的数据库:
使用的数据库是 PostgreSQL 9.6,ONLY_FULL_GROUP_BY 处于活动状态。
我尝试了什么
我现在已经花了几个小时尝试使用几乎类似于以下内容的查询来查询数据(使用 Drupal 的数据库服务select 接口):
SELECT n.id, n.title, COUNT(c.cid)+COUNTr.cid) AS comments
FROM nodes n
LEFT JOIN comments c
ON c.type = "node" AND n.id = c.entity_id AND c.status = 1
LEFT JOIN comments r
ON r.type = "comment" AND c.id = r.entity_id AND r.status = 1
GROUP BY n.id, n.title, c.entity_id, r.entity_id
但在我的一生中,我只是想不出编写查询的正确方法。我的基本想法是选择基表节点,在此上左连接 cmets 的第一阶段,然后再次左连接对第一个连接的回复。但似乎我的数据库对我的查询有其他想法...¯\_(ツ)_/¯
我真的希望有人可以让我重回正轨。任何帮助是极大的赞赏!感谢您花时间阅读所有这些内容。
【问题讨论】:
标签: postgresql drupal group-by count drupal-8