当我尝试发送以下查询时:
SET @attempts=0;
SELECT mt1.TimeStamp, mt1.ReadAttempts - @attempts AS delta,
@attempts := mt1.ReadAttempts ReadAttempts
FROM OneWireStats mt1
WHERE SensorIndex=1 ORDER BY mt1.TimeStamp;
在表OneWireStats中的行之间获取增量值我收到以下错误:
查询失败并显示错误:您的SQL语法出错;校验 与您的MySQL服务器版本对应的手册 在'SELECT mt1.TimeStamp,mt1.ReadAttempts - @attempts附近使用的语法 AS delta,@ attempts:= mt1.Re'在第1行查询= SET @ attempts = 0; SELECT mt1.TimeStamp,mt1.ReadAttempts - @attempts AS delta,@ attempts := mt1.ReadAttempts ReadAttempts FROM OneWireStats mt1 WHERE SensorIndex = 1 ORDER BY mt1.TimeStamp;,查询号码:0
当我将上面的错误打印输出中的查询粘贴到mysql客户端时,它可以正常工作。
mysql> SET @attempts=0; SELECT mt1.TimeStamp, mt1.ReadAttempts - @attempts AS delta, @attempts := mt1.ReadAttempts ReadAttempts FROM OneWireStats mt1 WHERE SensorIndex=1 ORDER BY mt1.TimeStamp LIMIT 10; Query OK, 0 rows affected (0.01 sec) +---------------------+-------+--------------+ | TimeStamp | delta | ReadAttempts | +---------------------+-------+--------------+ | 2013-12-23 07:55:01 | 5532 | 5532 | | 2013-12-23 08:00:00 | 302 | 5834 | | 2013-12-23 08:05:01 | 302 | 6136 | | 2013-12-23 08:10:00 | 302 | 6438 | | 2013-12-23 08:15:00 | 302 | 6740 | | 2013-12-23 08:20:01 | 302 | 7042 | | 2013-12-23 08:25:00 | 302 | 7344 | | 2013-12-23 08:30:01 | 302 | 7646 | | 2013-12-23 08:35:00 | 302 | 7948 | | 2013-12-23 08:40:01 | 302 | 8250 | +---------------------+-------+--------------+ 10 rows in set (0.07 sec)
我使用以下php代码:
$query = mysql_real_escape_string(trim($queryobj[$counter]));
$sqlresult = mysql_query($query) or die("Query failed with error: ".mysql_error() .
" Query = " . $query . ", Query no: " . $counter);
我的查询中没有使用任何单引号或双引号,因此我还不了解错误打印输出。
很有提示。
答案 0 :(得分:3)
您需要单独运行每个查询,可能像
mysql_query( "SET @attempts=0" );
mysql_query( "SELECT mt1.TimeStamp, mt1.ReadAttempts - @attempts AS delta, @attempts := mt1.ReadAttempts ReadAttempts FROM OneWireStats mt1 WHERE SensorIndex=1 ORDER BY mt1.TimeStamp" );
或使用mysqli的multi_query(),例如:
$query = "SET @attempts=0;";
$query .= "SELECT mt1.TimeStamp, mt1.ReadAttempts - @attempts AS delta, @attempts := mt1.ReadAttempts ReadAttempts FROM OneWireStats mt1 WHERE SensorIndex=1 ORDER BY mt1.TimeStamp";
mysqli_multi_query($connection, $query);
mysqli_next_result($connection);
if ($result = mysqli_store_result($connection)) {
//while loop here
}