存储函数 returns 0 mysql

stored function returns 0 mysql

我将此存储函数设为 return 每个客户的发票金额:

delimiter //
CREATE FUNCTION function1(id INT) RETURNS INT READS SQL DATA 
BEGIN 
    DECLARE result INT;
        (SELECT count(invoice_id) INTO @result FROM invoices WHERE customer_id = @id);
    RETURN @result;
END//
delimiter ;

但是当我使用它时,returns 0:

SELECT function1(12) AS Q;

和查询 returns 428 :

SELECT count(invoice_id) AS Q FROM invoices WHERE customer_id = 12;

我需要知道我做错了什么。

@id 与 id

不同

但是最好使用变量名_id来区分变量和列名

delimiter //
CREATE FUNCTION function1(_id INT) RETURNS INT READS SQL DATA 
BEGIN 
    DECLARE result INT;
        (SELECT count(invoice_id) INTO @result FROM invoices WHERE customer_id = _id);
    RETURN @result;
END//
delimiter ;