1

假设我有这个代码:

$ids = execute_query("SELECT id FROM table WHERE field = 'value' ORDER BY order_field");
$query = "UPDATE table SET increment = CASE";
for ($i = 0; $i <= sizeof($ids); $i++) {
  $query .= " WHEN id = " . $ids[$i] . " THEN " . $i;
}
$query .= " END WHERE field = 'value'";

然后我执行那个查询。

有没有一种方法可以将SELECTand组合UPDATE成一个查询,从而有效地实现完全相同的目标?

4

3 回答 3

1

无法在子选择同一个表时更新表:http: //dev.mysql.com/doc/refman/5.6/en/update.html “目前,您无法更新表并从同一个表中选择一个子查询。”

我没有在这里运行它,但据我了解,这就是你想要的:

SET @ordering = 0;

UPDATE
  table SET increment = (@ordering := @ordering + 1)
WHERE
  field = 'value'
ORDER BY
  order_field;

只要不重新连接到数据库,就可以在单独的查询中执行SETand 。UPDATE

于 2013-04-03T16:01:22.520 回答
0

这可能会做你想要的:

update table
    set increment = (select cnt
                     from (select count(*) as cnt
                           from table t
                           where field = 'value' and t.id <= table.id
                          ) a
                    )
    where field = 'value';
于 2013-04-03T15:48:16.967 回答
0
SET @ordering = 100000;

UPDATE candidate 
    SET regno = (@ordering := @ordering + 1)
    WHERE 
        year = 2014 AND 
        confirm = 1 AND
        e_stat = 1 
    ORDER BY centre_code, `name`;
于 2014-05-01T16:22:54.650 回答