我需要创建一个MySQL游标,以便在遍历一个“巨大”(数百万个entires)表时跟踪当前的行号。
示例数据库表:

CREATE TABLE  test (
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
someText TEenter code hereXT NOT NULL
) ;

如果此表为1000000个条目,则执行以下查询:
select * from test where id >= 50;

然后根据需要在php脚本中处理数据(限制为1分钟)。如何跟踪已遍历“test”表的行?

最佳答案

// use a PHP session to store the id (could also use cookies...)
session_start();

// your 1 minute timeout
set_time_limit(60);

// query your results (may even put a known-out-of-reach limit on the
// query just to make sure you're not always pulling all the entries every
// reload (that would each up your timeout alone, depending)
$lastID = 0; // lowest possible ID value (e.g. MIN(id) )
if (session_is_registered('last_select_id'))
{
  $lastID =(int)$_SESSION['last_select_id'];
}
else
{
  session_register('last_select_id');
  $_SESSION['last_select_id'] = $lastID;
}
$dbResult = mysql_query("SELECT * FROM test WHERE id>{$lastID} ORDER BY id"/* LIMIT 10000 */);
if ($dbResult)
{
  while (($row = mysql_fetch_row($dbResult)) !== false)
  {
    // perform processing

    // mark as last processed (depending how many steps,
    // you may decide to move this from end to somewhere
    // else, just sh*t luck where your timeout occurs)
    $_SESSION['last_select_id'] = $row['id'];
  }
}

// it reached the end, save to assume we can remove the session variable
session_unregister('last_select_id');

我只能照你说的去做,尽管我觉得这应该是本地限制的,而不仅仅是等待PHP发出超时。
编辑另一个方法,扩展批处理的思想,是改变表并添加一个“已处理”列,您可以更新。
EDIT2也要小心。我确实设置/取消设置会话值。因此,如果刷新,即使页面加载成功,而不是出现超时错误($lastID将看不到会话变量,它将从1重新开始,然后继续执行),这可能会导致无限循环。

10-04 19:32