我有一些SQL代码在两个MySQL客户端中都按预期返回结果集,即MySQL Workbench和Sequel Pro。但是,当我将SQL代码放入存储过程(SP)中时,它会在Sequel Pro上返回一个包含一行(与以前不同)的结果集。SP在MySQL工作台上仍然运行良好(正确的结果集)。我不明白为什么。相同的 SQL 代码,相同的数据库,但两个不同的 SQL 客户端上的结果集不同。
我的最终目标是从 PHP 文件调用此 SP。当我这样做时,我得到的结果与Sequel Pro相同。您认为问题可能是什么?
这是我的SQL代码:
SET @prev_val:=24;
SET @num := 0;
SELECT @prev_date := DATE(MAX(logDate)) FROM EmotionsDB.`Log`;
SELECT @prev_date_outerLoop := DATE(MAX(logDate)) FROM EmotionsDB.`Log`;
SELECT dateOfEmotion, emotionID
FROM
(
SELECT dateOfEmotion, diffHour, emotionID,
@num := IF(dateOfEmotion = @prev_date_outerLoop, @num + 1, 1) AS row_number,
@prev_date_outerLoop := dateOfEmotion AS previousDate
FROM
(
SELECT DATE(logDate) AS dateOfEmotion, TIME(logDate) AS timeOfEmotion, emotionID,
IF(DATE(logDate) = @prev_date, @prev_val - HOUR(logDate), 24 - HOUR(logDate)) AS diffHour,
@prev_val:=HOUR(logDate) AS previousHour,
@prev_date:=DATE(logDate) AS previousDate
FROM EmotionsDB.Log
WHERE DATE(logDate) <> DATE(CURDATE()) AND MONTH(logDate) = MONTH(CURDATE())
ORDER BY DATE(logDate) DESC, TIME(logDate) DESC
) AS InnerSubQuery
ORDER BY dateOfEmotion DESC, diffHour DESC
) AS OuterSubQuery
WHERE row_number = 1;
这是我从MySQL Workbench获得的正确结果集(两列,"dateOfEmotion"和"emotionID"):
2014-02-17 6
2014-02-14 2
2014-02-13 2
2014-02-07 5
2014-02-06 2
2014-02-05 0
2014-02-02 3
这是我从 Sequel Pro 中的 SP 获得的错误结果集(只有一列列名为"@prev_date := DATE(MAX(logDate))"):
2014-02-17
提前谢谢。
似乎 SequelPro 正在返回临时结果集。您可以将变量赋值更改为 SELECT .. INTO
,如下所示:
SELECT DATE(MAX(logDate)) INTO @prev_date FROM EmotionsDB.`Log`;
SELECT DATE(MAX(logDate)) INTO @prev_date_outerLoop FROM EmotionsDB.`Log`;
禁止显示临时结果集。