我想在MySql中创建一个函数,并且我试图返回更大的值(两个值中的值)。 在我的代码中,这些值在变量X和Y中,这是我的代码:
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
我希望有人知道正确的方法,我会非常感谢分享答案:)
答案 0 :(得分: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)
);