1

2つのテーブルがあります。1つはチャットの統計を追跡するためのもので、もう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

返されるデータが次のように表示されるように、これら2つのクエリを1つにまとめたいと思います。

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

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 に答える
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 に答える