读取具有 31 个不同列的 mysql 表

我需要阅读一张代表每月登记的表格。有点像


year, month, name, d1...d31 <--days of the month

我使用这个函数来获取当月的全球小时数


function calchour($db, $table, $year, $month)

{

    $daysinmonth =cal_days_in_month(CAL_GREGORIAN, $month, $year);//Nbr of days in month

    $tt_hour = '0';

    $result = mysqli_query($db,"SELECT * FROM $table WHERE anno = '$year' AND month = '$month'") or merror($msg = mysqli_error($db));  

    while ($row = mysqli_fetch_array($result))

    {

        $volhr = '0';

        for ($i = '1'; $i <= $daysinmonth; $i++) {

            $day = 'd'.$i;

            $hour = $row[$day];

            if (($hour != '')) { $volhr = $volhr + $hour; }

        }

        $tt_hour = $tt_hour + $volhr;

    }

return $tt_hour;    

}

有没有更好的方法来获取当月的全球小时数?


慕田峪4524236
浏览 68回答 1
1回答

繁星coding

我将它们添加到sql中:SELECT SUM(&nbsp; &nbsp; coalesce(d1,0)+coalesce(d2,0)+coalesce(d3,0)+coalesce(d4,0)+coalesce(d5,0)+coalesce(d6,0)+coalesce(d7,0)+coalesce(d8,0)+coalesce(d9,0)+coalesce(d10,0)+coalesce(d11,0)+coalesce(d12,0)+coalesce(d13,0)+coalesce(d14,0)+coalesce(d15,0)+coalesce(d16,0)+coalesce(d17,0)+coalesce(d18,0)+coalesce(d19,0)+coalesce(d20,0)+coalesce(d21,0)+coalesce(d22,0)+coalesce(d23,0)+coalesce(d24,0)+coalesce(d25,0)+coalesce(d26,0)+coalesce(d27,0)+coalesce(d28,0)+coalesce(d29,0)+coalesce(d30,0)+coalesce(d31,0))) total_hours ...不过,最好重新组织数据库,为每个值分配一个单独的行。任何时候你有名为column1、column2等的列,这都是糟糕的数据库设计的标志。所以像这样:&nbsp;create table volhours (&nbsp; &nbsp; &nbsp;date date not null primary key,&nbsp; &nbsp; &nbsp;volhours int&nbsp;);并选择一系列日期的总小时数:&nbsp;select coalesce(sum(volhours),0) total_hours from volhours where date between '2020-01-01' and '2020-01-31';当然,您应该使用占位符。
打开App,查看更多内容
随时随地看视频慕课网APP