I have the following structure of data, with table names give in bold font and their pertinent column names below.
common_authorprofile:
{id, full_name, description, avatar_id, profile_id}
aldryn_people_person table:
{id, phone, ...}
aldryn_newsblog_article:
{id, is_published, is_featured, ..., author_id}
It bears noting that common_authorprofile.profile_id = aldryn_people_person.id
and aldryn_newsblog_article.author_id = aldryn_people_person.id
I am trying to compute the number of articles for each entity in common_authorprofile
.
This is how it is currently done:
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
My question is two-fold:
- is this a correct way of doing it, given the table relationship?
- is this an efficient way, i.e., is there a way to improve its speed and readability?