我有两个表,一个用于跟踪聊天统计信息,另一个用于跟踪邮件统计信息。
我目前的查询如下:
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
)
)
我怎样才能实现这样的目标?提前谢谢。
答案 0 :(得分: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)
答案 1 :(得分: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;
BTW:DATE_FORMAT(时间戳,'%b%e')不会产生'2012-11-09',DESC修饰符是否适用于GROUP BY表达式?