Question

i have a problem concerning a select query in MYSQL

i have two different tables and i want to obtain a certain result

i used COUNT method which gave me only the results (>=1)

But in reality , i want to use all counts with zero included how to do it?

My query is:

SELECT 
    first.subscriber_id, 
    second.tag_id,
    COUNT(*)
FROM 
    content_hits first  
    JOIN content_tag second ON first.content_id=second.content_id 
GROUP BY  
    second.Tag_id,first.Subscriber_id<br>

First table:Content_hits

CONTENT_ID  SUBSCRIBER_ID   
30          1   
10          10  
34          4   
32          2   
40          3 
28          3   
30          6   
31          8   
12          3 

Second table:Content_tag

CONTENT_ID   TAG_ID
1            1
2            1
3            1
4            1
5            1
6            1
7            1
8            1
9            1
10           1
11           2
12           2
13           2
14           2

Result but incomplete For example:Subsrciber6 for tag_id=1 should have a count(*)=0

subscriber_id   tag_id   COUNT(*)
1               1        4
2               1        7
3               1        2
4               1        1
5               1        3
7               1        2
8               1        1
9               1        1
10              1        3
1               2        2
2               2        3
3               2        2
Was it helpful?

Solution

Now that you have further elaborated on what you actually want to achieve, it can be seen that the problem is much more complex. You actually want all combinations of subscriber_id and tag_id, and then count the number of actual entries in the joined table product. whew. So here goes the SQL:

SELECT combinations.tag_id,
       combinations.subscriber_id,

-- correlated subquery to count the actual hits by tag/subscriber when joining
-- the two tables using content_id

       (SELECT count(*)
        FROM content_hits AS h
        JOIN content_tag AS t ON h.content_id = t.content_id
        WHERE h.subscriber_id = combinations.subscriber_id
        AND t.tag_id = combinations.tag_id) as cnt

-- Create all combinations of tag/subscribers first, before counting anything
-- This will be necessary to have "zero-counts" for any combination of
-- tag/subscriber

FROM (
  SELECT DISTINCT tag_id, subscriber_id
  FROM content_tag
  CROSS JOIN content_hits
) AS combinations

OTHER TIPS

Not sure, but is this what you want?

 SELECT first.subscriber_id, second.tag_id, COUNT(*) AS c 
 FROM content_hits first JOIN content_tag second ON first.content_id=second.content_id 
 GROUP BY second.Tag_id,first.Subscriber_id HAVING c = 0
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top