gpt4 book ai didi

mysql - 将我的两个查询优化为一个

转载 作者:行者123 更新时间:2023-11-30 23:25:47 25 4
gpt4 key购买 nike

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

我当前的查询是这样的:

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
)

)

我怎样才能实现这样的目标?提前谢谢你。

最佳答案

虽然 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 表达式?

关于mysql - 将我的两个查询优化为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13453275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com