表中的列直接划分

时间:2014-09-11 05:14:07

标签: php mysql

我有以下php脚本:     

$prevNum = 0;

$hostname = "localhost";
$database = "Consommation";
$username = "xxx";
$password = "yyy";

$db = mysql_connect($hostname, $username, $password); // fill in connection string

mysql_select_db("Consommation", $db);

$sql = 'update Consommation t1  
set diff=value-coalesce((select value from 
                (select id,value from Consommation) t2
                where t2.id<t1.id 
                order by t2.id desc limit 1),1)';

mysql_select_db('Consommation');
$retval = mysql_query( $sql, $db );
if(! $retval )
{
  die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);


?>

从表Consommation中填充列diff与两个连续行的差异,如:

id     date      time      value     diff
1  2013-01-27   9:37:41    49402      0
2  2013-01-27   9:40:08    49405      3
3  2013-01-27  10:22:01    49506     101

我想要做的是将差异直接除以100的列差异,如:

id     date      time      value     diff
1  2013-01-27   9:37:41    49402      0
2  2013-01-27   9:40:08    49405     0.03
3  2013-01-27  10:22:01    49506     1.01

我应该在PHP脚本(更新)中更改什么? 非常感谢

2 个答案:

答案 0 :(得分:1)

只需将100除以表达式:

$sql = 'update Consommation t1  
        set diff=(value-coalesce(
                    (select value 
                     from (select id,value from Consommation) t2
                     where t2.id<t1.id 
                     order by t2.id desc limit 1),1))/100';

答案 1 :(得分:0)

$sql = 'update Consommation t1  
        set diff=(value-coalesce((select value from 
            (select id,value from Consommation) t2
            where t2.id<t1.id 
            order by t2.id desc limit 1),1))/100';