MySQL:在特定时间范围内计算来自不同表的列

时间:2011-07-20 20:15:54

标签: mysql

我有以下查询:

SELECT SUM(COUNTED) AS TCOUNTED 
    FROM (SELECT COUNTED FROM `clicks`.`t1`
          UNION ALL
          SELECT COUNTED FROM `clicks`.`t2`
          UNION ALL
          SELECT COUNTED FROM `clicks`.`t3`
         ) AS TMP

我在哪里以及如何添加时间限制?我希望它只计算在某些日期之间...对于MySQL noobness抱歉。

谢谢!

2 个答案:

答案 0 :(得分:3)

SELECT SUM(COUNTED) AS TCOUNTED 
    FROM (SELECT COUNTED FROM `clicks`.`t1` WHERE somedatecol BETWEEN somedate AND somedate
          UNION ALL
          SELECT COUNTED FROM `clicks`.`t2` WHERE somedatecol BETWEEN somedate AND somedate
          UNION ALL
          SELECT COUNTED FROM `clicks`.`t3` WHERE somedatecol BETWEEN somedate AND somedate
         ) AS TMP`

http://dev.mysql.com/doc/refman/5.0/en/select.html

答案 1 :(得分:2)

我认为最好的办法是在UNION语句之前在每个子选择中包含where子句。

SELECT SUM(COUNTED) AS TCOUNTED FROM
(SELECT COUNTED FROM clicks.t1 WHERE <fieldname> BETWEEN '<date1>' AND '<date2>'
   UNION ALL
SELECT COUNTED FROM clicks.t2 WHERE <fieldname> BETWEEN '<date1>' AND '<date2>'
   UNION ALL
SELECT COUNTED FROM clicks.t3 WHERE <fieldname> BETWEEN '<date1>' AND '<date2>')
AS TMP;

当然,这与您尝试使用查询完成的所有相关。