2014-07-05 76 views
0

如何获取引用者的所有线索和命中?来自不同不同表格的sql多个计数

表: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

为什么'xxxxxxxx'在你的样品输出引线5?我只在'leads_log'表中看到4。为什么'yyyyyy'只有1,'leads_log'表中有2个。 – Barmar

+0

我没有来自hit_log的hit,也没有来自lead logs独立存储的线索,所以它就是这样的 – Lucifer

+0

但'xxxxxxxx'只有4行'hits_log',为什么在结果中有'5'? – Barmar

回答

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 

DEMO

也许这实际上是你想要的。它限制命中和导致一个特定的主题,并将在任一表中包括零计数的查阅者。

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 

DEMO

+0

它只给一个单行如果两个referer对单个主题它不给第二行 – Lucifer

+0

我不确定你的意思。看看我的sqlfiddle演示。我并不完全确定你真正想要什么,因为你的示例输出看起来与示例输入不匹配 - 请在评论中看到我的问题。 – Barmar

+0

检查此演示我正在尝试http://www.sqlfiddle.com/#!2/2a216/1 – Lucifer