使用数组更新ORDER BY查询


UPDATE an ORDER BY query with an array

我有一个数组,它包含数字。有一个表,有两列:idnum

例如,数组为:(2, 7, 1, 0)

我想按id(ORDER BY ID DESC)对表进行排序,并使用数组元素按此顺序更新num值。

所以第一个元素num的值在顺序上,应该是2,第二个是7,等等…

是否可以只使用mySQL,或者我必须用PHP管理它?


示例:

表:

id | num
--------
 1 | 0
 5 | 0
 6 | 0
 11| 0

阵列:(5, 9, 10, -20)

查询后的表格:

id | num
--------
 1 | 5
 5 | 9
 6 | 10
 11|-20
SET @a=0;
UPDATE table1
LEFT JOIN (
  SELECT @a:=@a+1 as i,
    id
  FROM table1
  ORDER BY id
) as t
ON table1.id = t.id
SET table1.num= ELT(t.i, 5, 9, 10, -20)

使用PHP逐行更新更好。

用一句简单的话来说,你可以做这样的事情:

$array = array(5,9,10 -20);
$i = 0;
$q = 'select id from `table` order by id desc limit ' . count($array);
// use some sql magic here - PDO or mysqli to get results
while ($row = $sql_result->fetch()) {
    $new_value = $array[$i];
    $id = $row['id'];
    $q = 'update `table` set `num` = ' . $new_value . ' where `id` = ' . $id;
    // more sql magic here. with prepared statements etc
    $i++;
    // and increase $i to get next array value
}