如果您要进行这样的多次更新,那么通常我会建议您进行 INSERT,但在 id 已经存在时使用重复键条件进行更新。这样,您可能会执行一个 SQL 查询,而不是对表中的每条记录执行一个查询。
mysql_query("INSERT INTO matches (id, delta)
VALUES
($idp1, $delta1),
($idp2, $delta2),
($idp3, $delta3),
($idp4, $delta4)
ON DUPLICATE KEY UPDATE delta=VALUES(delta)
");
编辑
这是我在进行多次插入/更新时有时会使用的一个 php 类(这里是稍微简化的版本)
<?php
class table_process
{
var $link;
var $row_array = array();
var $field_name_store = '';
var $table_name = '';
var $record_count = 0;
var $update_clause = '';
var $rows_to_process = 255;
function __CONSTRUCT($link, $table_name, $update_clause = '')
{
$this->link = $link;
$this->table_name = $table_name;
$this->update_clause = $update_clause;
}
function __DESTRUCT()
{
if (count($this->row_array) > 0)
{
$this->process_rows();
}
}
function field_names($in_field_names)
{
$this->field_name_store = "(`".implode("`,`", $in_field_names)."`)";
}
function record_count()
{
return count($this->record_count);
}
function make_row($in_row)
{
$ret = true;
foreach($in_row AS &$in_field)
{
$in_field = (($in_field == null) ? "NULL" : "'".mysql_real_escape_string($in_field, $this->link)."'");
}
$this->record_count++;
$this->row_array[] = "(".implode(",", $in_row).")";
if (count($this->row_array) > $this->rows_to_process)
{
$ret = $this->process_rows();
}
return $ret;
}
function process_rows()
{
$ret = true;
$sql = "INSERT INTO ".$this->table_name." ".$this->field_name_store." VALUES ".implode(",", $this->row_array)." ".$this->update_clause;
if (!mysql_query($sql, $this->link))
{
$ret = false;
}
$this->row_array = array();
return $ret;
}
public function set_rows_to_process($rows_to_process)
{
if (is_numeric($rows_to_process) and intval($rows_to_process) > 0)
{
$this->rows_to_process = $rows_to_process;
}
}
}
?>
然后你可以像下面这样使用它:-
$ProcessMatches = new table_process($link, 'matches', ' ON DUPLICATE KEY UPDATE delta=VALUES(delta)', true);
$ProcessMatches->field_names(array('id', 'delta'));
$ProcessMatches ->make_row(array('id'=>$id1, 'delta'=>$delta1));
$ProcessMatches ->make_row(array('id'=>$id2, 'delta'=>$delta2));
$ProcessMatches ->make_row(array('id'=>$id3, 'delta'=>$delta3));
$ProcessMatches ->make_row(array('id'=>$id4, 'delta'=>$delta4));
$ProcessMatches ->make_row(array('id'=>$id5, 'delta'=>$delta5));
$ProcessMatches ->make_row(array('id'=>$id6, 'delta'=>$delta6));
unset($ProcessMatches);
该类采用连接链接和表名/列名,以及更新子句(如果需要)。
您插入的每一行都由该类获取并为插入而构建。一旦准备好插入 255 行,它就会插入它们并擦除存储它们的数组。完成后,取消设置触发 __DESTRUCT 方法的对象,该方法执行最终插入。