2016-01-04 31 views
1

我想在MySQL中建立一個功能更大價值,我想返回值(出兩個值),這是更大的。 在我的代碼,這些值在變量X和Y,這裏是我的代碼:MySQL的功能 - 讓使用IF語句

DELIMITER ;; 
CREATE FUNCTION getMaxDistanceById(id int(11)) 
RETURNS INT 
BEGIN 
DECLARE X INT DEFAULT 0;   
DECLARE Y INT DEFAULT 0; 

SELECT MAX(distance) INTO X FROM trainings WHERE user_id = id; 
SELECT MAX(trainings.distance) INTO Y FROM trainings INNER JOIN attendings ON trainings.tid = attendings.tid WHERE attendings.uid = id; 
IF X <= Y THEN 
    SET X = Y; 
RETURN X; 
END 
;; 

而在phpMyAdmin執行此語句,我得到的錯誤是:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 12 

我希望有人知道該怎麼做了正確的方式,我會分享答案:)

回答

2

你缺少一個END IF非常感謝。

整個東西可以簡化爲使用GREATEST(返回最大它的參數)的單個表達式。

RETURN GREATEST(
    (SELECT MAX(distance) FROM trainings WHERE user_id = id), 
    (SELECT MAX(trainings.distance) FROM trainings INNER JOIN attendings ON trainings.tid = attendings.tid WHERE attendings.uid = id) 
); 
+0

非常感謝您,加入END IF解決了問題,並且簡化後的表達式完美無缺! :) – gorczyca94