mysql函数变量集不工作

4zcjmb1e  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(365)

我正在写一个函数,它应该返回一个浮动值。

BEGIN

DECLARE due_amount DECIMAL(9,2);
  SET due_amount = (SELECT due_amount FROM (
                SELECT id,  MAX(date), due_amount, user_id
                FROM lunch_transaction
                GROUP BY user_id
                HAVING user_id = user) l);
  IF due_amount IS NULL THEN
    SET due_amount = 0.00;
  END IF;
  RETURN due_amount;
END

函数只返回值 0.00 即使价值应该是别的。
仅运行此查询:

(SELECT due_amount FROM (
            SELECT id,  MAX(date), due_amount, user_id
            FROM lunch_transaction
            GROUP BY user_id
            HAVING user_id = user) l);

但是给出了正确的输出。
如何将查询的输出设置为变量?

a9wyjsp7

a9wyjsp71#

使用可能与列名冲突的变量名是非常糟糕的做法。而且,子查询似乎非常不必要。我会尝试更像这样的方法:

BEGIN
    DECLARE v_due_amount DECIMAL(9,2);

    SELECT v_due_amount := l.due_amount
    FROM lunch_transaction l
    WHERE l.user_id = in_user;  -- I'm guessing `user` is also a parameter

    IF v_due_amount IS NULL THEN
        SET v_due_amount = 0.00;
    END IF;
    RETURN v_due_amount;
END;

您的版本在子查询中具有聚合函数。这毫无意义,因为 due_amount 不是聚合函数的参数。这种逻辑或许应该是:

SELECT v_due_amount := SUM(l.due_amount)
    FROM lunch_transaction l
    WHERE l.user_id = in_user;  -- I'm guessing `user` is also a variable

相关问题