3

我有一个关于 MYSQL 中的选择查询的问题

我有两个不同的表,我想获得某个结果

我使用了 COUNT 方法,它只给了我结果(> = 1)

但实际上,我想使用所有计数为零包括怎么做?

我的查询是:

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>

第一个表:Content_hits

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

第二个表: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

结果但不完整例如:Subsrciber6 for tag_id=1 应该有一个 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
4

2 回答 2

2

现在您已经进一步详细说明了您实际想要实现的目标,可以看出问题要复杂得多。您实际上想要 和 的所有组合subscriber_idtag_id然后计算联接表产品中的实际条目数。哇。所以这里是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
于 2012-03-29T11:33:51.517 回答
0

不确定,但这就是你想要的吗?

 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
于 2012-03-29T11:32:31.357 回答