使用mysql_query()更新带有数字序列的表行

时间:2022-03-29 21:05:47

I need to set a field in some rows to numbers in a sequence (0, 1, 2, ... ). Normally this should work:

我需要在某些行中将字段设置为序列中的数字(0,1,2,...)。通常这应该工作:

SET @counter:=-1;
UPDATE nodes SET sort=@counter:=@counter+1 WHERE parent_id=2

But multiple queries with mysql_query() cannot be done. Is there a way to accomplish this in a single query or should I just run multiple queries in a loop?

但是无法使用mysql_query()进行多次查询。有没有办法在单个查询中完成此操作,还是应该在循环中运行多个查询?

1 个解决方案

#1


2  

Try doing a join:

尝试加入:

UPDATE nodes cross join (select @counter := -1) const
    SET sort = (@counter:=@counter + 1)
    WHERE parent_id = 2;

#1


2  

Try doing a join:

尝试加入:

UPDATE nodes cross join (select @counter := -1) const
    SET sort = (@counter:=@counter + 1)
    WHERE parent_id = 2;