MySQL join / union来自更多表

时间:2011-10-15 18:38:41

标签: mysql

我有一系列MySQL表,其中第一列是Unix时间格式的日期,第二列是每个表格具有不同格式的一些数据。

我使用与此类似的查询按月对数据进行分组:

SELECT YEAR(FROM_UNIXTIME(date)) AS year, MONTH(FROM_UNIXTIME(date)) AS month, SUM(views) AS views,
FROM stats
GROUP BY year, month

我需要什么样的查询才能在按行分组的一行中输出所有这些“第二”列? 即每个返回的行包含“年,月,视图,列2,列3”......

我尝试过使用UNION,但是,由于“第二”列都不同,它会为每个表返回一行。比如:

year1, month1, views, 0, 0...  
year1, month1, 0, column2, 0...  
year1, month1, 0, 0, column3...  
year2, month2, views, 0, 0...  
year2, month2, 0, column2, 0...  
year2, month2, 0, 0, column3...

1 个答案:

答案 0 :(得分:1)

您必须执行以下操作:

SELECT MAX(views) as views,
    MAX(column2) as column2,
    MAX(column3) as column3
FROM (
    SELECT YEAR(FROM_UNIXTIME(date)) AS year, 
        MONTH(FROM_UNIXTIME(date)) AS month, 
        SUM(views) AS views,
        0 AS column2,
        0 AS column3
    FROM stats
    GROUP BY year, month
    UNION
    SELECT YEAR(FROM_UNIXTIME(date)) AS year, 
        MONTH(FROM_UNIXTIME(date)) AS month, 
        0 AS views,
        sum(column2) AS column2,
        0 AS column3
    FROM stats
    GROUP BY year, month
    UNION
    SELECT YEAR(FROM_UNIXTIME(date)) AS year, 
        MONTH(FROM_UNIXTIME(date)) AS month, 
        0 AS views,
        0 AS column2,
        sum(column3) AS column3
    FROM stats
    GROUP BY year, month
)
GROUP BY year, month;

由于每个选择包含相同的列,因此您将能够聚合整个事物并选择每行的最大值。显然,如果您的数据是非数字或小于0,则必须替换不同的聚合函数。