如何获得引用者的所有线索和点击量?
表:hits_log
+-----------+----------+
| topic | referer |
+-----------+----------+
| topic0614 | xxxxxxxx |
| topic0614 | xxxxxxxx |
| topic0615 | zzzzz |
| topic0615 | yyyyyy |
| topic0614 | xxxxxxxx |
| topic0614 | xxxxxxxx |
| topic0615 | zzzzz |
| topic0615 | yyyyyy |
| topic0614 | yyyyyy |
| topic0614 | yyyyyy |
| topic0615 | zzzzz |
| topic0615 | yyyyyy |
+-----------+----------+
表:leads_log
+-----------+----------+
| topic | referer |
+-----------+----------+
| topic0614 | xxxxxxxx |
| topic0614 | xxxxxxxx |
| topic0614 | xxxxxxxx |
| topic0615 | zzzzz |
| topic0615 | yyyyyy |
| topic0614 | xxxxxxxx |
| topic0615 | zzzzz |
| topic0614 | yyyyyy |
+-----------+----------+
我想要这样的结果
如果使用主题topic0614
+-----------+----------+------------+
| referer | hits | leads |
+-----------+----------+------------+
| xxxxxxxx | 4 | 4 |
| yyyyyy | 2 | 1 |
+-----------+----------+------------+
我试过了
SELECT h.referer, COUNT(h.referer) as hits, COUNT(l.referer) as leads FROM `hits_log` h ,`leads_log` l
WHERE h.topic='topic0614' and h.referer=l.referer
GROUP BY h.referer
但它无效
任何人都可以帮助我吗?谢谢。
答案 0 :(得分:4)
您需要在子查询中分别对每个表进行分组。如果您在主查询中进行计数,则需要计算交叉积的结果,这会导致乘法。
SELECT h.referer, hits, leads
FROM (SELECT referer, COUNT(*) AS hits
FROM hits_log
WHERE topic = 'topic0614'
GROUP BY referer) AS h
JOIN (SELECT referer, COUNT(*) AS leads
FROM leads_log
GROUP BY referer) AS l
ON h.referer = l.referer
也许这实际上就是你想要的。它限制了命中和导致特定主题,并且将包括任一表中零计数的引用。
SELECT referer, MAX(hits) AS hits, MAX(leads) AS leads
FROM (SELECT referer, COUNT(*) AS hits, 0 as leads
FROM hits_log
WHERE topic = 'topic0614'
GROUP BY referer
UNION
SELECT referer, 0 AS hits, COUNT(*) as leads
FROM leads_log
WHERE topic = 'topic0614'
GROUP BY referer) AS x
GROUP BY referer