php - 有没有更好的方法来为多个表编写 AVG() SQL 查询(或改进我的代码的方法)
问题描述
我对管理具有大量数据的 sql 查询有点陌生,并且我试图提高请求的性能。我的问题是我有多个具有相同结构的不同名称的表,因此我必须从所有表中平均 temp 的值以供以后使用。
我目前正在使用此代码:
//these value changes on each request, here are some examples to help you understand
$ano_desde = 2019;
$mes_hasta = 4;
$id_t = 1123;
//
for ($ano = $ano_desde; $ano <= $ano_hasta; $ano++) {
for ($mes = $mes_hasta; $mes <= 12; $mes++) {
$sql = " SELECT AVG(temp) FROM table".$ano."_".$mes." WHERE id_t = $id_t";
//HERE I WOULD SEND THE QUERY TO MY DB AND SAVE RESP ON $TEMP
$temp = queryResp;
if ($temp != 0) {
$temps[] = floatval($temps);
}
}
}
这确实有效,但它对我的响应造成了 4 到 5 秒的打击,我很想改进它,无论是在 php 代码中还是在我的查询中。
在此先感谢,对于任何拼写错误,我深表歉意,因为英语不是我的母语。
解决方案
我认为你正在寻找的是看起来像它会加入所有表然后做一个 avg 的 sql。(如果你对每张桌子都这样做,你会得到平均值的平均值。
SELECT AVG(temp) from (
SELECT temp FROM table.ano._mes1 WHERE id_t = id_t
UNION ALL
SELECT temp FROM table.ano._mes1 WHERE id_t = id_t
UNION ALL
SELECT temp FROM table.ano._mes1 WHERE id_t = id_t
) a
实际上你打电话也这样做以获得更好的性能
SELECT s/c avgtmp from (
SELECT sum(temp) s, count(temp) c FROM table.ano._mes1 WHERE id_t = id_t
UNION ALL
SELECT sum(temp) s, count(temp) c FROM table.ano._mes1 WHERE id_t = id_t
UNION ALL
SELECT sum(temp) s, count(temp) c FROM table.ano._mes1 WHERE id_t = id_t
) a
推荐阅读
- ruby-on-rails - 如何验证子关联的选定 ID 在保存时对于父级是唯一的?
- sql - sql,使用ID删除重复记录
- javascript - HTML5 验证约束 - setCustomValidity 和 novalidate
- reactjs - 为什么通过 mapStateToProps 传递给 props 后状态仍未定义?
- javascript - 在函数之外获取推文 ID 数组
- python - PyArmor - 打包成一个可执行文件
- ruby-on-rails - 语法错误,意外的输入结束,预期结束 - 我的代码缺少“结束”,我不知道为什么
- docker - Docker 环境变量在运行命令时无法通过 shell 脚本
- postgresql - 我如何知道我的应用程序是否容易受到 CVE-2020-13692 的攻击?
- php - 试图在单击编辑按钮时获取非对象的属性“id”