简体   繁体   中英

Read next or previous mysql rows and update current row without using cursors or auto-incremented value

I need to process some records that are in a mysql table.The problem is the incrementable id is not a reliable way of knowing what the next or previous record is because some records are deleted.

My table has three fields.

Id,Number,Status

.

I want to read the numbers one at a time and I don't mind fetching it from the database every time I want to read the next or previous.Once i get the number,i want to double it and write the value to the column status.

The use of cursor would be nice but cursors wouldn't allow me update the underlying table i am reading from.Is there a solution that can allow me read the next and previous value and at the same time allow me update the current row?.

Thanks.

I am not saying this is the best way, it could be done like this though:

$rows=SELECT id FROM <table>;

foreach($rows as $row){
  $prev=SELECT number FROM <table> WHERE id < $row ORDER BY id DESC LIMIT 1;
  $next=SELECT number FROM <table> WHERE id > $row ORDER BY id ASC LIMIT 1;
  if($prev && $next)
    UPDATE <table> SET = 2($prev+$next) WHERE id=$row;
}

Well, the similar thing can be achieved through cursor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM