在SQL操作方面,我不是太先进了。我在横幅系统中有以下4个表来宣传我的博客:
banners
-id
-other irrelevant data
clicks
-id
-bid (banner id)
-other irrelevant data
exits (people who clicked on the banner and never used the blog or registered an account)
-id
-bid
postregistered (used the banner and register to the blog)
-id
-bid
现在,我想生成一个简单的报告,向我展示每个横幅的total number of clicks
,exits
和reg's
。
我试过了:
SELECT COUNT(c.id) as clicks, COUNT(e.id) as exits, COUNT(r.id) as reg
FROM banners b
LEFT JOIN clicks c
ON c.bid = b.id
LEFT JOIN exits e
ON e.bid = b.id
LEFT JOIN registered r
ON r.bid = b.id
GROUP BY b.name
但它只是让mysql终止我的处理器并且永远不会完成,没有足够的数据使它成为一个沉重的查询。
请帮助我,对不起,如果这看起来非常基本。
编辑:
我可以运行每个Left连接自己的并获得正确的结果但我宁愿将其作为单个查询运行
答案 0 :(得分:3)
您面临的问题是每个横幅都有一个小型笛卡尔积。简单来说,横幅ID不足以链接表格。
假设你有10个横幅。每个横幅有100次点击。在这些点击中,有50个是退出,50个是注册的。你可能认为你会得到1000行以外的东西。
不,你得到了所有这些产品:10 * 100 * 50 * 50 = 2,500,000。这是很多处理。
您需要某种用户ID来跟踪用户点击退出和注册的点击次数。或者,您可以预先汇总您的查询:
select b.bid, b.name, numclicks, numexits, numreg
from banner b left outer join
(select bid, count(*) as numclicks
from clicks
group by bid
) c left outer join
on c.bid = b.bid join
(select bid, count(*) as numexits
from exits
group by bid
) e
on e.bid = b.bid left outer join
(select bid, count(*) as numreg
from postregistered
group by bid
) r
on r.bid = b.bid