Mysql - 分组后加入两个表

时间:2013-12-25 09:02:33

标签: mysql sql select join group-by

我在以下结构中有两个表:

Table - a
datetime            | camapgin_id | country | unique_id
2013-12-23 10:23:59 |     123     |    US   |  5475642385763


Table - b
datetime            | camapgin_id | country | unique_id
2013-12-23 10:40:35 |     123     |    US   |  5475642385763

我想查询生成如下表:

Table - joined
day        | camapgin_id | country | count(1) from a | count(1) from b
2013-12-23 |     123     |    US   |       100       |      82

我可以使用自己的查询生成每个表,如下所示:

SELECT date_format(datetime, '%Y-%m-%d') AS day, campaign_id, country, count(1)
FROM a
GROUP BY day, campaign_id, country

对于表b也是如此,但这会让我看到两个不同的表。

如何使用与我发布的查询相同的group by加入这两个表?

1 个答案:

答案 0 :(得分:3)

试试这个:

SELECT DATE_FORMAT(A.day, '%Y-%m-%d') AS day, A.campaign_id, A.country, MAX(tableACount), MAX(tableBCount)
FROM (SELECT DATE(datetime) AS day, campaign_id, country, COUNT(1) tableACount
      FROM a GROUP BY day, campaign_id, country
     ) AS A
INNER JOIN (SELECT DATE(datetime) AS day, campaign_id, country, COUNT(1) tableBCount
            FROM b GROUP BY day, campaign_id, country
           ) AS B ON A.day = B.day AND A.campaign_id = B.campaign_id AND A.country = B.country
GROUP BY A.day, A.campaign_id, A.country

修改::

SELECT DATE_FORMAT(A.day, '%Y-%m-%d') AS DAY, A.campaign_id, A.country, MAX(tableACount), MAX(tableBCount)
FROM (SELECT DATE(DATETIME) AS DAY, campaign_id, country, COUNT(1) tableACount, 0 AS tableBCount
      FROM a GROUP BY DAY, campaign_id, country
      UNION 
      SELECT DATE(DATETIME) AS DAY, campaign_id, country, 0 AS tableACount, COUNT(1) tableBCount
      FROM b GROUP BY DAY, campaign_id, country
     ) AS A
GROUP BY A.day, A.campaign_id, A.country