一个字段的Mass sql更新有多个值?

时间:2012-09-16 13:42:47

标签: php mysql sql-update

我有一个看起来像这样的数组:

array(
    [0] => 1
    [1] => 2
    [2] => 4
    [3] => 3
)

目前,我正在遍历数组并按照

的顺序运行单个更新
foreach($array as $position => $id){
   //query = update users set order = ($position+1) where id = $id
}

显然不是实际的代码,但它得到了重点,

如果我的列表中有1000个项目,那就是1000个查询,

我想知道是否有办法在一个查询中执行此操作?

4 个答案:

答案 0 :(得分:3)

您可以使用MySQL案例陈述。我不确定它是否会更快或更快,但这是它的工作方式:

$query = 'UPDATE users SET order = CASE id ';
foreach($array as $position => $id) {
    $query .= 'WHEN '.$id.' THEN "'.($position+1).'" ';
}
$query .= 'ELSE order ENDCASE'; // leave order the same if the id doesn't match the array
// run $query...

MySQL CASE Syntax

答案 1 :(得分:0)

实际上是可能的。 您可以使用循环来构建查询字符串以适合此example

然后执行您的查询;)

答案 2 :(得分:0)

假设id是主键或唯一键,您可以这样做:

$tmp = Array();
foreach($array as $position=>$id) {
    $tmp[] = "(".$id.",".($position+1).")";
}
$query = "INSERT INTO users (id,order) VALUES ".implode(",",$tmp)
    ." ON DUPLICATE KEY UPDATE order=VALUES(order)";

答案 3 :(得分:0)

使用“in”运算符 - 更新用户设置order =($ position + 1),其中id为

相关问题