【问题标题】:Using a mysql user-defined function to calculate dollar amount. Error 1064 (42000)使用 mysql 用户定义的函数来计算美元金额。错误 1064 (42000)
【发布时间】:2018-03-27 05:07:40
【问题描述】:

我正在尝试创建一个 mysql 函数来计算商店中前五名客户的总支出,但我不断收到以下语法错误。是什么导致了错误? 错误:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near
'FUNCTION costofbestbuyers (totalspent DECIMAL)
RETURNS DOUBLE
BEGIN
    DECLA' at line 1

功能:

DELIMITER // 
CREATE FUNCTION topfivespenders (totalspent DECIMAL) 
RETURNS DOUBLE 
BEGIN 
    DECLARE totalspent DOUBLE DEFAULT 0; 

    SELECT sum(ordercost) AS totalspent
      FROM customer c JOIN orders o 
      ON c.customerID = o.cID 
      GROUP BY o.cID 
      ORDER BY totalspent desc 
      LIMIT 5; 

RETURN totalspent; 
END; //

【问题讨论】:

    标签: mysql user-defined-functions


    【解决方案1】:

    sum(ordercost) 的值设置为totalspent 变量的语法不正确。

    试试这个。希望这行得通。

    DELIMITER // 
    CREATE FUNCTION topfivespenders (totalspent DECIMAL) 
    RETURNS DOUBLE 
    BEGIN 
        DECLARE totalspent DOUBLE DEFAULT 0; 
    
        SELECT sum(ordercost) INTO totalspent
          FROM customer c JOIN orders o 
          ON c.customerID = o.cID 
          GROUP BY o.cID 
          ORDER BY totalspent desc 
          LIMIT 5; 
    
    RETURN totalspent; 
    END//
    DELIMITER //
    

    【讨论】:

      【解决方案2】:

      由于您在执行操作时遇到语法错误,我想您正在尝试在 phpMyAdmin 或使用 API 中执行此操作。您不需要在这些环境中使用 DELIMITER 技巧。只有在使用 mysql 客户端执行 SQL 语句或 SQL 脚本时才需要 DELIMITER。看这个问题的答案:Creating functions in phpMyAdmin - Error: access denied you need the super privilege for this operation

      除此之外,我发现您的功能还存在一些其他问题。如果你没有成功定义函数,你还没有遇到这些问题。

      • MySQL 存储函数只能返回标量,不能返回结果集。您正在尝试返回最多包含五个分组总和的结果集。

      • 1234563排序顺序。就好像您没有排序顺序一样,MySQL 将以某种任意方式对行进行排序。

      【讨论】:

        猜你喜欢
        • 2011-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多