子查询GROUP BY运算符
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了子查询GROUP BY运算符相关的知识,希望对你有一定的参考价值。
我有一张卡片和帖子表,每张卡片和帖子条目至少有2个标签。当前查询使用card_to_tags_link
和post_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
是否可以将作者查询作为子查询并将结果作为数组返回?
答案
你想要ARRAY_AGG()
吗?
SELECT card,
count(post.id) AS count_1,
max(post.date) AS max_1,
ARRAY_AGG(DISTINCT post.author_url)
以上是关于子查询GROUP BY运算符的主要内容,如果未能解决你的问题,请参考以下文章
sql中 group by 的优先级高 还是 join的优先级高?