子查询GROUP BY运算符

时间:2019-04-05 04:00:13

标签: sql postgresql

我有一张卡片和帖子表,每个卡片和帖子条目至少有2个标签。当前查询使用card_to_tags_linkpost_to_tags_link表来获取按特定卡分组的所有帖子。

SELECT 
  card,
  count(post.id) AS count_1, 
  max(post.date) AS max_1

FROM 
  card 
  JOIN card_to_tags_link ON card.id = card_to_tags_link.card_id 
  JOIN post_to_tags_link ON post_to_tags_link.post_tags @>card_to_tags_link.card_tags 
  JOIN post ON post_to_tags_link.post_id = post.id 

GROUP BY 
  card.id 

现在,因为每个帖子都有一个post_owner列,所以我想按author_url汇总所有帖子,并按多个帖子进行排序:

SELECT ARRAY(post.author_url
from post
group_by post.author_url
order by count(post.id)
limit by 10)

这是一个单独执行的简单查询,但我想将它作为子查询添加到现有查询中:

SELECT 
  card,
  count(post.id) AS count_1, 
  max(post.date) AS max_1,
  **ADD SUBQUERY HERE**

FROM 
  card 
  JOIN card_to_tags_link ON card.id = card_to_tags_link.card_id 
  JOIN post_to_tags_link ON post_to_tags_link.post_tags @>card_to_tags_link.card_tags 
  JOIN post ON post_to_tags_link.post_id = post.id 

GROUP BY 
  card.id 

是否可以将作者查询作为子查询并将结果作为数组返回?

1 个答案:

答案 0 :(得分:0)

您只想要ARRAY_AGG()吗?

SELECT card,
       count(post.id) AS count_1, 
        max(post.date) AS max_1,
       ARRAY_AGG(DISTINCT post.author_url)