This is a very simple query you need:
First join the two table in the FROM
clause, using the foreign key column (channel_id
). We need to use LEFT JOIN
so all channels appear in the result set, even those with no subscribers and accesses at all.:
FROM
channels AS c
LEFT JOIN
channel_accesses AS ca
ON ca.channel_id = c.channel_id
Then we group by the primary key of channels
because we want a result for every channel:
GROUP BY
c.channel_id, c.channel_name
Finally, we can SELECT
the columns we want from channels
and the aggregate (SUM
of num_of_accesses
). The COALESCE()
function is added so we get 0s instead of nulls for channels without subscribers:
SELECT
c.channel_id,
c.channel_name,
COALESCE(SUM(ca.num_of_accesses), 0) AS total_num_of_accesses
FROM
channels AS c
LEFT JOIN
channel_accesses AS ca
ON ca.channel_id = c.channel_id
GROUP BY
c.channel_id, c.channel_name ;