1

我有两张表,一张用于跟踪聊天统计信息,一张用于跟踪邮件统计信息。

我当前的查询如下所示:

SELECT COUNT(id) as chat_amount, DATE_FORMAT(timestamp, '%b %e') as period FROM tblChats WHERE timestamp BETWEEN '{$start}' AND '{$end}' AND UserID = 0 GROUP BY DAY(timestamp) DESC, MONTH(timestamp) DESC, YEAR(timestamp) DESC

SELECT COUNT(id) as mail_amount, DATE_FORMAT(timestamp, '%b %e') as period FROM tblMails WHERE timestamp BETWEEN '{$start}' AND '{$end}' AND UserID = 0 GROUP BY DAY(timestamp) DESC, MONTH(timestamp) DESC, YEAR(timestamp) DESC

我想将这两个查询合并为一个,以便返回的数据如下所示:

Array ( 
[0] => Array ( 
    [period] => 2012-11-09 
    [chat_amount] => 1500 
    [mail_amount] => 100 
) 
[1] => Array ( 
    [period] => 2012-11-08 
    [chat_amount] => 500 
    [mail_amount] => 350 
) 
[2] => Array ( 
    [period] => 2012-11-07 
    [chat_amount] => 2000 
    [mail_amount] => 1300 
) 
[3] => Array ( 
    [period] => 2012-11-06 
    [chat_amount] => 1000 
    [mail_amount] => 970 
) 

)

我怎样才能实现这样的目标?先感谢您。

4

2 回答 2

0

尝试这个:

SELECT A.period, chat_amount, mail_amount FROM (
(SELECT COUNT(id) AS chat_amount, DATE_FORMAT(TIMESTAMP, '%b %e') AS period FROM tblChats WHERE TIMESTAMP BETWEEN '{$start}' AND '{$end}' AND UserID = 0 GROUP BY DAY(TIMESTAMP) DESC, MONTH(TIMESTAMP) DESC, YEAR(TIMESTAMP) DESC) AS A 
LEFT JOIN 
(SELECT COUNT(id) AS mail_amount, DATE_FORMAT(TIMESTAMP, '%b %e') AS period FROM tblChats WHERE TIMESTAMP BETWEEN '{$start}' AND '{$end}' AND UserID = 0 GROUP BY DAY(TIMESTAMP) DESC, MONTH(TIMESTAMP) DESC, YEAR(TIMESTAMP) DESC) AS B ON A.period = B.period)
UNION 
SELECT A.period, chat_amount, mail_amount FROM (
(SELECT COUNT(id) AS chat_amount, DATE_FORMAT(TIMESTAMP, '%b %e') AS period FROM tblChats WHERE TIMESTAMP BETWEEN '{$start}' AND '{$end}' AND UserID = 0 GROUP BY DAY(TIMESTAMP) DESC, MONTH(TIMESTAMP) DESC, YEAR(TIMESTAMP) DESC) AS A 
RIGHT JOIN 
(SELECT COUNT(id) AS mail_amount, DATE_FORMAT(TIMESTAMP, '%b %e') AS period FROM tblChats WHERE TIMESTAMP BETWEEN '{$start}' AND '{$end}' AND UserID = 0 GROUP BY DAY(TIMESTAMP) DESC, MONTH(TIMESTAMP) DESC, YEAR(TIMESTAMP) DESC) AS B ON A.period = B.period)
于 2012-11-19T12:03:30.463 回答
0

虽然 Saharsh 的答案似乎以您想要的格式为您提供了结果 - 这是一个非常昂贵的查询。

由于您已将预期输出引用为序列化的 PHP 数组,这意味着您正在使用 PHP 来处理数据。一种更有效的方法是使用以下查询,然后将数据合并到 PHP 数组中:

 SELECT rtype, DATE_FORMAT(iperiod, '%b %e') AS period, amount
 FROM
 (SELECT 'chat' AS rtype,
   COUNT(id) as amount, 
   DATE(timestamp) as iperiod 
   FROM tblChats 
   WHERE timestamp BETWEEN '{$start}' AND '{$end}' 
   AND UserID = 0 
   GROUP BY DATE(timestamp)
 UNION
   SELECT 'mail' as rtype, 
   COUNT(id) as mail_amount, 
   DATE(timestamp) as iperiod 
   FROM tblMails 
   WHERE timestamp BETWEEN '{$start}' AND '{$end}' 
   AND UserID = 0 
 GROUP BY DATE(timestamp)) ilv
 ORDER BY period DESC;

顺便说一句:DATE_FORMAT(timestamp, '%b %e') 不会产生 '2012-11-09',DESC 修饰符是否适用于 GROUP BY 表达式?

于 2012-11-19T12:25:31.443 回答