[英]sql multi count from different different table
如何获得推荐人的所有线索和点击?
表格: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
但这没用
谁能帮我吗? 谢谢。
您需要在子查询中将每个表分别分组。 如果您在主查询中进行计数,那么您正在计算叉积的结果,这会导致乘法。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.