我是MySQL的初学者,我正试图根据case-when子句中的条件执行不同的准备语句。问题是要找到STATION表的LAT_N列的中值,对于偶数和奇数条LAT_N记录,我想使用Case。
这是我为特殊情况准备的声明:
SET @foo = (SELECT ROUND((COUNT(*)-1)/2) FROM STATION);
PREPARE STMT1 FROM 'SELECT ROUND(LAT_N,4) FROM STATION ORDER BY LAT_N LIMIT ?,1';
EXECUTE STMT1 USING @foo;
这是为偶数:
SET @foo1 = (SELECT ROUND(COUNT(*)/2) FROM STATION);
SET @foo2 = (SELECT ROUND((COUNT(*)+2)/2) FROM STATION);
PREPARE STMT2 FROM 'SELECT ROUND((((SELECT ROUND(LAT_N,4) FROM STATION ORDER BY LAT_N LIMIT ?,1) + (SELECT ROUND(LAT_N,4) FROM STATION ORDER BY LAT_N LIMIT ?,1))/2),4)';
EXECUTE STMT2 USING @foo1, @foo2;
我的想法与这个代码有点相似:
SELECT CASE WHEN COUNT(*)%2=0 THEN EXECUTE STMT2 USING @foo1, @foo2
ELSE EXECUTE STMT1 USING @foo
FROM STATION
END;
但该代码返回错误1064(42000(,所以我想知道是否有其他选择。非常感谢
我已经找到了答案,其中包括使用过程
DELIMITER $$
CREATE PROCEDURE latmed()
BEGIN
IF (SELECT COUNT(*) FROM STATION)%2=0 THEN
SET @foo1 = (SELECT ROUND(COUNT(*)/2) FROM STATION);
SET @foo2 = (SELECT ROUND((COUNT(*)+2)/2) FROM STATION);
PREPARE STMT2 FROM 'SELECT ROUND((((SELECT ROUND(LAT_N,4) FROM STATION ORDER BY LAT_N LIMIT ?,1) + (SELECT ROUND(LAT_N,4) FROM STATION ORDER BY LAT_N LIMIT ?,1))/2),4)';
EXECUTE STMT2 USING @foo1, @foo2;
ELSE
SET @foo = (SELECT ROUND((COUNT(*)-1)/2) FROM STATION);
PREPARE STMT1 FROM 'SELECT ROUND(LAT_N,4) FROM STATION ORDER BY LAT_N LIMIT ?,1';
EXECUTE STMT1 USING @foo;
END IF;
END$$
DELIMITER ;
CALL latmed()
我认为它有点长,所以如果有人有一个较短的代码可以回答我的问题。感谢