mysql报告连接表和数据库结构问题

时间:2015-05-26 11:59:14

标签: php mysql database-design database-schema

我正在努力实现以下报告结果:

campaign_name   visits  leads   registrations
3333              3       0         0
direct            3       2         1
(null)            0       1         1
test              0       1         1

我有这个数据库结构,现在我很确定关系是不正确的。我一起玩他们加入他们,但我做错了 http://sqlfiddle.com/#!9/451de/7

您的建议将不胜感激。

2 个答案:

答案 0 :(得分:0)

试试这个

mysql_query("select  campaign_name  , count(t.id) 
             as visits, count(l.id) as leads ,count(r.id) as registrations

from trackings t

left join leads as l
 on l.tracking_id =t.id

left join registrations as r
 on r.tracking_id =t.id

where t.created_at between '2015-04-01' AND '2015-05-31' and t.aff_id =5

group by campaign_name");

答案 1 :(得分:0)

试试这个。

SELECT `campaign_name`, 
   count(t.id) as visits, 
   count(l.id) as leads ,
   count(r.id) as registrations

FROM `trackings` t

   LEFT JOIN leads l ON t.`id` = l.`tracking_id` 
   LEFT JOIN registrations r ON t.`id` = r.`tracking_id`

WHERE t.created_at between '2015-04-01'
      AND '2015-05-31' 
      AND t.aff_id =5

GROUP BY `campaign_name`

ORDER BY visits DESC

因为日期问题而不是您要找的东西。 跟踪表 ID

6           2015-04-07 18:54:57
26          2015-04-13 11:06:13
50          2015-04-20 14:42:23

while lead

26         2015-05-13 11:07:09
50         2015-05-20 14:43:07