PostgreSQL - 具有两个很多关系的SELECT

时间:2017-01-25 11:49:40

标签: sql postgresql join many-to-many relational-database

上下文:我有一个与TAGS和CATEGORIES相关的表POST(所有many2many关系)。即使他们没有任何TAGS或CATEGORIES,我也希望退回帖子。

示例

 - POST1 with TAG1, TAG2 and CAT1  
 - POST2 WITH CAT3, CAT4, CAT5
 - POST3

我想回来:

 - POST1 / {TAG1, TAG2} / {CAT1}
 - POST2 / NULL / {CAT3, CAT4, CAT5}
 - POST3 / NULL / NULL

但我有:

 - POST1 / {TAG1, TAG2} / {CAT1, NULL, NULL}
 - POST2 / {NULL, NULL} / {CAT3, CAT4, CAT5}
 - POST3 / {NULL, NULL} / {NULL, NULL, NULL}

如果屏幕截图不起作用,我的部分关系代码:

`FROM bmb_blog_post as post 
LEFT OUTER JOIN bmb_blog_category_bmb_blog_post_rel as posts_categories ON posts_categories.post_id = post.id
LEFT OUTER JOIN bmb_blog_category as category ON category.id = posts_categories.category_id
LEFT OUTER JOIN bmb_blog_post_bmb_blog_tag_rel as posts_tags ON posts_tags.post_id = post.id 
LEFT OUTER JOIN bmb_blog_tag as tag ON tag.id = posts_tags.tag_id`

PgAdmin SQL Results Screenshot

1 个答案:

答案 0 :(得分:0)

如果我理解正确,那么方法是使用两个子查询,在进行最终连接之前聚合

SELECT p.id, pc.categories, pt.tags
FROM bmb_blog_post p LEFT OUTER JOIN
     (SELECT pc.post_id, array_agg(c.category) as categories
      FROM bmb_blog_category_bmb_blog_post_rel pc JOIN
           bmb_blog_category c
           ON c.id = pc.category_id
      GROUP BY pc.post_id
     ) pc
     ON pc.post_id = p.id LEFT OUTER JOIN 
     (SELECT pt.post_id, array_agg(t.tag) as tags
      FROM bmb_blog_post_bmb_blog_tag_rel pt JOIN
           bmb_blog_tag t
           ON t.id = pt.tag_id
      GROUP BY pt.post_id
     ) pt
     ON pt.post_id = p.id ;

如果你的帖子有多个类别多个标签,那么你的结果会更加古怪。