0

我有以下数据结构,表名以粗体显示,下面的相关列名。

common_authorprofile:

{id, full_name, description, avatar_id, profile_id}

aldryn_people_person 表:

{id, phone, ...} 

aldryn_newsblog_article:

{id, is_published, is_featured, ..., author_id}

值得注意的是,common_authorprofile.profile_id = aldryn_people_person.idaldryn_newsblog_article.author_id = aldryn_people_person.id

我正在尝试计算common_authorprofile.

这是目前的做法:

SELECT main.*, sub.article_count
FROM common_authorprofile AS main
INNER JOIN aldryn_people_person
ON aldryn_people_person.id = main.profile_id,
LATERAL 
    (SELECT author_id, COUNT(*) as article_count
     FROM aldryn_newsblog_article AS sub
     WHERE
            sub.author_id = aldryn_people_person.id   AND
            sub.app_config_id = 1            AND
            sub.is_published IS TRUE         AND
            sub.publishing_date <= now()     AND
        aldryn_people_person.id = sub.author_id 
     GROUP BY author_id
    ) AS sub

我的问题有两个:

  • 鉴于表关系,这是一种正确的做法吗?
  • 这是一种有效的方法吗,即有没有办法提高它的速度和可读性?
4

1 回答 1

1

退出aldryn_people_person混音使这更容易阅读。

为了可读性,我也更喜欢公共表表达式而不是子查询或横向连接,但 CTE 会减慢执行速度。只有当速度有问题时,我才会重构。

我会这样处理它:

with article_counts as (
  select author_id, count(*) as article_count
    from aldryn_newsblog_article
   where app_config_id = 1
     and is_published
     and publishing_date <= now()
   group by author_id
)
select prof.*, coalesce(ac.article_count, 0) as article_count
  from common_authorprofile prof
       left join article_counts ac
              on ac.author_id = prof.profile_id;

left outer join您购买所有common_authorprofile记录的检索。将CTE 中coalesce()缺少的行显示为。如果这不是您想要的,您可以将其更改为。article_counts0left joinjoin

如果您有任何问题,请发表评论。

于 2020-07-29T17:59:54.523 回答