Domanda

I am trying to set up a few queries for a MySQL database of tables containing details of video channels and subscribers to these channels. One of the queries attempts to list all the existing channels and how many times each channel has been accessed by any of the subscribers. In this query I am not interested which subscriber has accessed a channel but simply the list of all channels and TOTAL times each channel has ever been accessed. It probably is a very simple query, but I am just starting playing with databases, so please don't blast me. For this I am using two of tables created (in short) with:

CREATE TABLE channels (channel_id, channel_name, channel_descr);

CREATE TABLE channel_accesses (channel_id, subscriber_id, access_date, num_of_accesses);

I have tried to select all channel_ids and names from the 'channels' table and count() or sum() the num_of_accesses in channel_access but I come up with some funny results as I actually didn't know how to put the two together properly. In table channel_accesses, num_of_accesses stores how many times a subscriber has accessed a particular channel. So what I need is to total somehow how many times a channel was accessed by any of the subscribers (sorry, I think I repeated myself here).

È stato utile?

Soluzione

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 ;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top