如何从mysql数据库表列的较低值中减去上限值

时间:2015-04-21 03:37:31

标签: php mysql

我有一个像这样的MySQL数据库表

-------------------------------------------
name     | distancefromstart  |  distance
-------------------------------------------    
AA       |    90              |
BB       |    50              |
CC       |    100             |
DD       |    10              |

首先,我想按distancefromstart列的值对此表进行排序。 对表格进行排序后,distancefromstart的第一个值应从distancefromstart的第二个值减去,distancefromstart的第二个值应减去distancefromstart的第三个值和第三个值{ distancefromstart应该从distancefromstart的第四个值中减去,依此类推。

然后应将新值添加到数据库中名为distance的列中。

然后更新的表应该是这样的:

name     | distancefromstart  |  distance
-------------------------------------------
AA       |    10              |  40 
BB       |    50              |  40
CC       |    90              |  10
DD       |    100             |   

2 个答案:

答案 0 :(得分:0)

这将计算您想要的值:

select t1.name, t1.distancefromstart, t2.distancefromstart - t1.distancefromstart distance 
from t t1
  left join t t2
  on t1.distancefromstart < t2.distancefromstart
where not exists (
  select 1 
    from t t3 
    where t3.distancefromstart > t1.distancefromstart 
      and t3.distancefromstart < t2.distancefromstart
  )
order by t1.distancefromstart asc;

演示小提琴:http://sqlfiddle.com/#!9/d9f70/1

如果你想更新源表,只需要将该查询加入到表中,并进行更新,如下所示:

update t inner join (select t1.name, t1.distancefromstart, t2.distancefromstart - t1.distancefromstart distance 
from t t1
  left join t t2
  on t1.distancefromstart < t2.distancefromstart
where not exists (
  select 1 
    from t t3 
    where t3.distancefromstart > t1.distancefromstart 
      and t3.distancefromstart < t2.distancefromstart
  )
order by t1.distancefromstart asc) r 
on t.name = r.name and t.distancefromstart = r.distancefromstart SET t.distance = r.distance;

示例:http://sqlfiddle.com/#!9/b6819/1

答案 1 :(得分:0)

假设我们有“测试”数据库,“距离”表格包含here等数据。

现在让我们品尝一些旧飞机弃用的PHP代码:

<?php
// :) omg, connect to database
mysql_connect('127.0.0.1', 'root', 'root');
mysql_select_db('test');

// extract data to array
$distances = [];
$q = mysql_query("SELECT * FROM distances ORDER BY distancefromstart");
while ($d = mysql_fetch_assoc($q)) $distances[] = $d;

// reset distances cause it may contain rubbish
mysql_query("UPDATE distances SET distance=0");

$d_prev = null; // distance before current
foreach ($distances as $d) {
    if (null !== $d_prev) {
        // distance is the diff between current distancefromstat and prev
        $distance = $d['distancefromstart'] - $d_prev['distancefromstart'];
        mysql_query('
            UPDATE distances 
            SET distance='.$distance.' 
            WHERE name="'.mysql_real_escape_string($d_prev['name']).'"'
        );
    }
    $d_prev = $d; // current will be prev on next loop
}