2017-10-15 75 views
0

我正在嘗試創建一個mysql函數來計算商店中前五位客戶所花費的總額,但我一直收到以下語法錯誤。什麼導致了錯誤? 錯誤:使用mysql用戶定義的函數來計算美元金額。錯誤1064(42000)

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; // 

回答

0

語法不正確設置的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 // 
0

既然你得到了一個語法錯誤,那麼你會嘗試在phpMyAdmin或API中執行此操作。您不需要在這些環境中執行DELIMITER技巧。當您使用mysql客戶端執行SQL語句或SQL腳本時,您只需要DELIMITER。看到這個問題的答案:Creating functions in phpMyAdmin - Error: access denied you need the super privilege for this operation

除此之外,我看到你的函數的一些其他問題。如果您沒有成功定義函數,您還沒有遇到這些問題。

  • MySQL存儲的函數只能返回一個標量,而不是結果集。您試圖返回最多五個分組總和的結果集。

  • 你的ORDER BY子句是由你給沒有價值,除了默認的0值的局部變量totalspent這意味着你的ORDER BY子句將在一個恆定值,這使得每行的排序順序並列順序排序。這就好像你沒有排序順序一樣,MySQL將以某種任意的方式排序行。