将两个表合并为一个

时间:2013-07-09 12:55:59

标签: php mysql

我们有两个MySQL表来跟踪每天的横幅统计信息。一个用于视图的表和一个用于点击的表。两个表都设置如下:

点击次数:

banner_id (int 11)
click_date (date)
click_total (int 11)

查看:

banner_id (int 11)
view_date (date)
view_total (int 11)

我需要每个月获得统计数据;为此,我得到了这个查询(对于视图):

SELECT 
  bv.`view_date`,
  SUM(bv.`view_total`) AS view_total 
FROM
  tarlo.`tarlo_banners_views` bv 
WHERE bv.`banner_id` = 469 
GROUP BY bv.`banner_id` 
ORDER BY bv.`view_date` ASC ;

对于点击,我有一个看起来几乎相同的查询。在PHP中,我们将 date 的结果合并到一个数组中。现在我们想知道是否可以通过一个MySQL查询(而不是2个)来组合结果。

所以我们需要这样的结果:

Date:       Clicks:   Views:
2013-07-07  556       156833
2013-07-08  726       175683
2013-07-09  356       130588

而不是像这样的2个结果集:

Date:       Clicks:
2013-07-07  556
2013-07-08  726
2013-07-09  356

Date:       Views:
2013-07-07  156833
2013-07-08  175683
2013-07-09  130588

我们怎么做?

2 个答案:

答案 0 :(得分:1)

类似的东西:

SELECT 
  bv.`view_date`,
  SUM(bv.`view_total`) AS view_total,
  SUM(bc.`click_total`) AS click_total,
FROM
  tarlo.`tarlo_banners_views` bv, tarlo.`tarlo_banners_clicks` bc
WHERE bv.`banner_id` = 469
AND bc.`banner_id` = bv.`banner_id`
AND bc.`click_date` = bv.`view_date`
GROUP BY bv.`banner_id`
ORDER BY bv.`view_date` ASC ;

答案 1 :(得分:0)

你需要JOIN这两个表:

SELECT 
    bv.`view_date`,
    SUM(bv.`view_total_views`) AS view_total_views,
    SUM(bc.`view_total_clicks`) AS view_total_click
FROM
    tarlo.`tarlo_banners_views` bv
JOIN
    tarlo.`tarlo_banners_clicks` bc
WHERE bv.`banner_id` = 469 
GROUP BY bv.`banner_id` 
ORDER BY bv.`view_date` ASC ;