通过PostgreSQL中多个内部联接的条件进行计数

时间:2019-02-22 15:42:53

标签: sql postgresql join group-by window-functions

我有下表:

User
UserPostView
Post

UserPostView是一个联接表,其中包含有关查看帖子后User是否已投票,已投票或已通过的其他信息。

Post的列postable_type表示帖子的类型(TextPostImagePost等)。

我想为按postable_type分组的每个用户计算赞成票,反对票和通过计数。

我当前的查询非常慢,我可以肯定它可以轻松优化。

SELECT
    U.id,
    count((UP.postable_type = 'text_post' AND UPV.passed = true) OR NULL) as text_posts_pass_count,
    count((UP.postable_type = 'text_post' AND UPV.upvote = true) OR NULL) as text_posts_upvote_count,
    count((UP.postable_type = 'text_post' AND UPV.downvote = true) OR NULL) as text_posts_downvote_count,
    count((UP.postable_type = 'image_post' AND UPV.passed = true) OR NULL) as image_posts_pass_count,
    count((UP.postable_type = 'image_post' AND UPV.upvote = true) OR NULL) as image_posts_upvote_count,
    count((UP.postable_type = 'image_post' AND UPV.downvote = true) OR NULL) as image_posts_downvote_count
FROM
    users U
    INNER JOIN(
        SELECT
            user_id,
            post_id,
            passed,
            upvoted,
            downvoted
        FROM 
            user_post_views
    ) UPV on U.id :: TEXT = UPV.user_id :: TEXT
    INNER JOIN(
        SELECT
            id,
            postable_type
        FROM
            posts
    ) UP on UPV.post_id :: TEXT = UP.id :: TEXT
GROUP BY
    U.id

1 个答案:

答案 0 :(得分:1)

不要为联接进行类型转换!我认为您只需要:

SELECT UPV.user_id,
       COUNT(*) FILTER (WHERE p.postable_type = 'text_post' AND upv.passed) as text_posts_pass_count,
       COUNT(*) FILTER (WHERE p.postable_type = 'text_post' AND upv.upvote) as text_posts_upvote_count,
       COUNT(*) FILTER (WHERE p.postable_type = 'text_post' AND upv.downvote ) as text_posts_downvote_count,
       COUNT(*) FILTER (WHERE p.postable_type = 'image_post' AND upv.passed) as image_posts_pass_count,
       COUNT(*) FILTER (WHERE p.postable_type = 'image_post' AND upv.upvote) as image_posts_upvote_count,
       COUNT(*) FILTER (WHERE p.postable_type = 'image_post' AND upv.downvote) as image_posts_downvote_count
FROM user_post_views upv JOIN
     posts p
     ON upv.post_id = p.id 
GROUP BY upv.user_id;

更改:

  • 请勿对联接进行类型转换!这肯定会阻碍优化器。
  • users表似乎不是必需的。
  • 不需要子查询。
  • FILTER比条件聚合要快一些。更重要的是,意图更加明确。