首页 > 解决方案 > 有没有更好的方法来为多个表编写 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 代码中还是在我的查询中。

在此先感谢,对于任何拼写错误,我深表歉意,因为英语不是我的母语。

标签: phpmysqlsqlloopsaverage

解决方案


我认为你正在寻找的是看起来像它会加入所有表然后做一个 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

推荐阅读