如何在使用会话变量时在存储过程内运行此查询

时间:2011-04-29 12:45:28

标签: mysql sql stored-procedures

我在calculate medians

找到了此查询
@myvar:=0;
@rownum:=0;
SELECT result.readdate, 
       AVG(total_gallons) AS total_gallons 
FROM   (SELECT middle_rows.readdate, 
               numerated_rows.rownum, 
               numerated_rows.total_gallons 
        FROM   (SELECT IF(@myvar = readdate, @rownum := @rownum + 1, @rownum := 0) AS rownum,
                       @myvar := readdate                                          AS readdate_alias,
                       total_gallons 
                FROM   _temp_total_gallons 
                ORDER  BY readdate, 
                          total_gallons) numerated_rows, 
               (SELECT readdate, 
                       COUNT(*) / 2 median 
                FROM   _temp_total_gallons
                GROUP  BY readdate) middle_rows 
        WHERE  numerated_rows.rownum BETWEEN ( middle_rows.median - IF(median = ROUND(median), 1, 0) - 0.5 ) AND ( middle_rows.median - IF(median = ROUND(median), 0, 0.5) )
               AND numerated_rows.readdate_alias = middle_rows.readdate) result
GROUP  BY readdate

如您所见,它使用@myvar@rownum作为会话变量SELECT IF(@myvar = readdate, @rownum := @rownum + 1, @rownum := 0)

问题是无法在存储过程中运行此问题,因为@myvar:=0语法未知,我必须引用/设置内部选择运行时。

您如何重写上述查询以在存储过程中使用?

要测试的样本数据和查询可以在https://gist.github.com/948250发现 要测试的第二组数据是https://gist.github.com/25b991396d0dd6968b7e

1 个答案:

答案 0 :(得分:1)

使用

SET @myvar := 0;
在SP内部

分配值:

DELIMITER $$

CREATE PROCEDURE prc_median()
BEGIN
SET @myvar:=0;
SET @rownum:=0;
SELECT result.readdate,
       AVG(total_gallons) AS total_gallons
FROM   (SELECT middle_rows.readdate,
               numerated_rows.rownum,
               numerated_rows.total_gallons
        FROM   (SELECT IF(@myvar = readdate, @rownum := @rownum + 1, @rownum := 0) AS rownum,
                       @myvar := readdate                                          AS readdate_alias,
                       total_gallons
                FROM   _temp_total_gallons
                ORDER  BY readdate,
                          total_gallons) numerated_rows,
               (SELECT readdate,
                       COUNT(*) / 2 median
                FROM   _temp_total_gallons
                GROUP  BY readdate) middle_rows
        WHERE  numerated_rows.rownum BETWEEN ( middle_rows.median - IF(median = ROUND(median), 1, 0) - 0.5 ) AND ( middle_rows.median - IF(median = ROUND(median), 0, 0.5) )
               AND numerated_rows.readdate_alias = middle_rows.readdate) result
GROUP  BY readdate;
END;
$$