简体   繁体   English

过滤查询并保留完整的聚合数据

[英]filter query and keep full aggregate data

I have this database:我有这个数据库:

create table if not exists blog
(
    id                          serial        primary key,
    domain                      text
);

create table if not exists blog_category
(
    id          serial        primary key,
    name        text
);

create table if not exists blog_to_blog_category
(
    id               serial        primary key,
    blog_id          integer not null
        constraint "FK_blog_to_blog_category_blog_BlogId"
            references blog,
    blog_category_id integer not null
        constraint "FK_blog_to_blog_category_blog_category_BlogCategoryId"
            references blog_category
);


INSERT INTO blog VALUES
    (1, 'one.com'),
    (2, 'two.com'),
    (3, 'three.com');

INSERT INTO blog_category VALUES
    (1, 'business'),
    (2, 'marketing'),
    (3, 'misc');

INSERT INTO blog_to_blog_category VALUES
    (1, 1, 1),
    (2, 1, 2),
    (3, 1, 3),
    (4, 2, 1),
    (5, 2, 3);

I can get the data in format that I want by making a query like this:我可以通过这样的查询以我想要的格式获取数据:

select b.id, b.domain, coalesce( array_agg(bc.name) 
    filter (where bc.id is not null), '{}' ) as cats
from blog b
left join blog_to_blog_category bt on bt.blog_id = b.id
left join blog_category bc on bc.id = bt.blog_category_id
group by b.id

在此处输入图像描述

However, I can't work out how to filter it and also keep each record showing all categories it is in. for example:但是,我不知道如何过滤它并让每条记录显示它所在的所有类别。例如:

select b.id, b.domain, coalesce( array_agg(bc.name) 
    filter (where bc.id is not null), '{}' ) as cats
from blog b
left join blog_to_blog_category bt on bt.blog_id = b.id
left join blog_category bc on bc.id = bt.blog_category_id

where bc.name = 'marketing'
group by b.id

在此处输入图像描述

It filters the blog correctly but now I can't aggregate all categories into a field.它可以正确过滤博客,但现在我无法将所有类别汇总到一个字段中。 It only shows 1 category the blog is in.它只显示博客所在的 1 个类别。

What is the simplest way to be able to filter blogs and get a list of all of their categories?能够过滤博客并获得所有类别列表的最简单方法是什么?

Try to select blog_id from blog_to_blog_category by blog_category.name尝试通过blog_idblog_to_blog_category中选择blog_category.name

select b.id, b.domain, coalesce( array_agg(bc.name) 
    filter (where bc.id is not null), '{}' ) as cats
from blog b
left join blog_to_blog_category bt on bt.blog_id = b.id
left join blog_category bc on bc.id = bt.blog_category_id

where bt.blog_id = (
    select bt.blog_id from blog_to_blog_category bt
    left join blog_category bc on bc.id = bt.blog_category_id
    where bc.name = 'marketing'
)
group by b.id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM