猿问

MySQL 查询直接在 MYSQL 中工作,但是在 php 中运行时,由于首先运行设置查询而出现错误

我正在尝试在我的 PHP 脚本中运行以下脚本来计算运行总数。


<?php // Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection

if ($conn->connect_error) {

    die("Connection failed: " . $conn->connect_error);

}


$sql = "set @csum := 0; select  date(`DATE`) as dadate,  Price , (@csum := @csum + Price) as cumulative_sum from Profits WHERE Strat = 'arm' order by dadate;";

$result = $conn->query($sql)or die($conn->error);


if ($result->num_rows > 0) {

    // output data of each row

    while($row = $result->fetch_assoc()) {


        echo "{time: '" . $row["Date"]. "', value: ".$row["cumulative_sum"]. "},<br>";

    }

} else {

    echo "0 results";

}

$conn->close(); ?>

我相信我收到了以下错误,因为我一次运行 2 个查询,但一次只应该执行一个查询。


检查与您的 MySQL 服务器版本相对应的手册,以daDATE在第 1 行的“选择日期(),价格,(@csum := @csum + Price)作为累积_ ”附近使用正确的语法


有什么办法可以解决这个问题,需要将 :csum 设置为 0 以确保它从 0 开始


慕码人8056858
浏览 167回答 2
2回答

繁星淼淼

严格来说,这是不正确的,但我找不到它不工作的例子(在 MySQL 8.0 之前的版本中)......SELECT DATE(`daDATE`) date&nbsp; &nbsp; &nbsp;, Price&nbsp; &nbsp; &nbsp;, (@csum := @csum + Price) as cumulative_sum&nbsp;&nbsp; from Profits&nbsp;&nbsp; &nbsp; &nbsp;, (SELECT @csum := 0) vars&nbsp;&nbsp;WHERE Strat = 'arm'&nbsp;&nbsp;ORDER&nbsp;&nbsp; &nbsp; BY daDATE;请注意,因为您将结果传递给应用程序代码,所以您可以轻松地处理那里的累积算术

慕雪6442864

另一个初始化变体(没有 SELECT,如果您需要它是单表,主要对 UPDATE 有用):SELECT DATE(`daDATE`) date&nbsp; &nbsp; &nbsp;, Price&nbsp; &nbsp; &nbsp;, (@csum := @csum + Price) as cumulative_sum&nbsp;&nbsp; from Profits&nbsp;WHERE Strat = 'arm'&nbsp;&nbsp; &nbsp;AND (@csum := 0) = 0&nbsp;ORDER&nbsp;&nbsp; &nbsp; BY daDATE;
随时随地看视频慕课网APP
我要回答