MySql嵌套选择,变量不适用于PHP

时间:2017-06-15 11:07:49

标签: php mysql mysqli

我有一个嵌套的mysql查询,每6行给我一个表列(poutput_edat)的平均值

    set @rownum := 0;
    set @sum := 0;

    SELECT the_avg FROM (   
    select poutput_edat,   @rownum := (@rownum + 1) as rownum,    
    @sum := IF(@rownum mod 6 = 1,0 + poutput_edat,@sum + poutput_edat)
    as running_sum,   IF(@rownum mod 6 = 0,@sum / 6,NULL) as the_avg   
    from raw_edat /*WHERE date_edat = CURDATE()*/ ORDER BY invTime_edat desc)
    as average

我在使用php mysqli查询时遇到问题,它完全可以直接查询数据库。这是php mysql的限制吗?

1 个答案:

答案 0 :(得分:0)

您可以尝试在单独的FROM子句中声明变量,例如:

SELECT the_avg FROM (   
    select poutput_edat,   @rownum := (@rownum + 1) as rownum,    
    @sum := IF(@rownum mod 6 = 1,0 + poutput_edat,@sum + poutput_edat)
    as running_sum,   IF(@rownum mod 6 = 0,@sum / 6,NULL) as the_avg   
    FROM raw_edat /*WHERE date_edat = CURDATE()*/, (SELECT @rownum := 0, @sum := 0) a 
    ORDER BY invTime_edat desc)
    as average