我有一个关于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
结果但不完整 例如:tag_id = 1的Subsrciber6应该具有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
现在,您已经进一步详细说明了您实际想要实现的目标,可以看出该问题要复杂得多。你真正想要的所有组合subscriber_id和tag_id,再算上在连接表产品实际的条目数。。所以这是SQL:
subscriber_id
tag_id
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