1

我对 PHP 和 MySQL 很陌生,所以提前抱歉。我正在尝试执行一个查询,该查询计算一列的最近 30 行的总和,并将结果插入到表中的不同列中。

这是代码:

$link = mysqli_connect(DBHOST, DBUSER, DBPASS, DBNAME);

$sql1 = ("SELECT sum(open) FROM (SELECT date,open FROM AA ORDER BY date DESC LIMIT 30) sumopen30");
$result = mysqli_query($link,$sql1);

$resultarray = mysqli_fetch_assoc($result);
$attempts = $resultarray["open"];

echo $attempts;

$sql2 = "INSERT INTO AA (sum) VALUES ('$attempts')";
mysqli_query($link,$sql2);

我没有得到任何结果、更新或错误。如果我将查询更改为“SELECT open FROM AA WHERE open > 40”,则会回显数据,但我认为查询存在问题。任何意见,将不胜感激。

4

2 回答 2

0

问题是,总和没有存储在 open - 该字段被命名sum(open)

您还可以简化查询并给 sum(open) 一个新名称

$link = mysqli_connect(DBHOST, DBUSER, DBPASS, DBNAME);

$sql1 = ("SELECT sum(open) as sum_open FROM AA ORDER BY date DESC LIMIT 30");
$result = mysqli_query($link,$sql1);

$resultarray = mysqli_fetch_assoc($result);
$attempts = $resultarray["sum_open"];

echo $attempts;

$sql2 = "INSERT INTO AA (sum) VALUES ('$attempts')";
mysqli_query($link,$sql2);
于 2013-02-16T17:14:54.277 回答
0

试试这个:

$sql1 = ("SELECT sum(open) as open FROM AA ORDER BY date DESC LIMIT 30");
$result = mysqli_query($link,$sql1);

$resultarray = mysqli_fetch_assoc($result);
$attempts = $resultarray["open"];

echo $attempts;

$sql2 = "INSERT INTO AA (sum) VALUES ($attempts)";
mysqli_query($link,$sql2);

我假设你num的字段是数字的。

于 2013-02-16T17:15:38.113 回答