2016-01-04 49 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