MySQL AVG函数返回0



我使用下面的代码来查询数据库。

mysql_query ("SELECT * FROM _$symbol ORDER BY date DESC;");     
$_10day = mysql_query ("SELECT AVG(close) FROM _$symbol limit 10;");
$_21day = mysql_query ("SELECT AVG(close) FROM _$symbol limit 21;");
$_50day = mysql_query ("SELECT AVG(close) FROM _$symbol limit 50;");
echo "$_10dayn";
echo "$_21dayn";
echo "$_50dayn";

mysql_query ("INSERT INTO _$symbol(_10day) VALUE ('$_10day');");
echo mysql_errno($sql) . ": " . mysql_error($sql). "n";

我需要从数据库中获得close的平均值,我使用AVG()函数,然后将返回值插入数据库。查询在mysql中工作,但是它们不通过脚本工作。它确实在数据库中输入了一个值,但它总是输入0。我做错了什么?

EDIT--找到解决方案

$get10 = mysql_query ("SELECT AVG( close ) AS CloseAverage from ( SELECT close FROM _$symbol ORDER BY date DESC limit 10 ) sub1 ;");

$row = mysql_fetch_assoc($get10); $_10day = $row['CloseAverage'];

if (!mysql_query ("UPDATE _$symbol SET _10day = $_10day, _21day = $_21day, _50day = $_50day, _100day = $_100day, _120day = $_120day, _150day = $_150day, _200day = $_200day, _240day = $_240day, _20dayVol = $_20dayVol, _50dayVol = $_50dayVol where date = '$date';")) { echo "Update query failed"; }

我错误地查询了它,显然它需要被选为子查询,解决方案在上面,它现在正在工作。

下面是一个关于如何管理多个结果行的示例:

function connect()
{
    $db = mysql_connect("localhost","username","password") or die("your error msg");
    mysql_select_db("database_name");
    return $db;
}
$db = connect();
$query = "SELECT value1 FROM my_table";
$result = mysql_query($query, $db);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
    // This one will loop through the data in your output//
    $outputValue = $row['value1'];
}

用于插入数据:

// Continued from the state above //
$query = "INSERT INTO table_name (column1) VALUES (value1)";
$result = mysql_query($query, $db) or die(mysql_error());

$_10day是一个mysql结果,而不是一个值。你不能只是把一个结果放入一个查询字符串中,然后期望它工作。

你需要先得到结果数据,例如;

while($row = mysql_fetch_assoc($_10day)) {
     $10day = $row['AVG(close)'];
}

然后您可以执行插入查询;

mysql_query ("INSERT INTO _$symbol (_10day) VALUES ('$10day')");

希望这能有所帮助。

相关内容

  • 没有找到相关文章

最新更新