MySQL按行数更新

MySQL按行数更新,mysql,Mysql,我需要按行的编号更新行(而不是AI ID,因为某些行可能会被删除)。我该怎么做? 我的意思是这样的: UPDATE cars SET idx = value WHERE row_number = i 我会在“for”语句中执行此操作,我是语句的整数。所以我会更新语句中的每一行 对不起,我的英语不好,谢谢 我不知道mysql,但你可以用php来实现 $row_number=? ;//the row no of mysql you want to change the id $id=? ;/

我需要按行的编号更新行(而不是AI ID,因为某些行可能会被删除)。我该怎么做? 我的意思是这样的:

UPDATE cars SET idx = value WHERE row_number = i
我会在“for”语句中执行此操作,我是语句的整数。所以我会更新语句中的每一行


对不起,我的英语不好,谢谢

我不知道mysql,但你可以用php来实现

$row_number=?   ;//the row no of mysql you want to change the id 
$id=? ;//the new id 
mysql_connect //do it yourself
$query="select 8 from tablename";  //the query
$result=mysql_query($qyery,$conn);
$count=0;
while($row=mysql_fetch_array($result)) // fetch each row one by one an put data in array $row
{
    $count++;     //increment count means the no of rows are incermented
    if($count==$rownumber)   //the row where you want to edit the id
    {
        $query1="update tablename set id='".$id."' where id=".$row["id"];  //new query on that particular row
        $result1=mysql_query($query1,$conn);
    }
}

这将起作用,只需根据您的使用修改此代码

以下是一个纯MySQL解决方案:

/*test data*/
create table foo (id int auto_increment primary key, a int);
insert into foo (a) values (10), (11), (12);

/*update statement*/
update foo
set a = 5
where id = (
   select id from (
      select id, @rownum:=@rownum + 1 as rownumber 
      from foo, (select @rownum:=0) vars order by id
   ) sq where rownumber = 2
);
结果:

| ID |  A |
-----|----|--
|  1 | 10 |
|  2 |  5 |
|  3 | 12 |
如果您对此有任何疑问,请随时提问

另外,请注意其中的
按id排序
。这很重要,因为在数据库中没有第一行或最后一行。从理论上讲,如果没有order by条款,每次都可能有不同的结果


您也可以看到它。

您使用的是哪种脚本语言,php?嗯。。。我正在使用Pawn,但是php解决方案可以帮助toothnx很多人,我刚刚编写了代码,很高兴它解决了您的问题problem@AdamSchauerbhawin的解决方案不是确定性的,因此容易出错。请考虑我的解决方案,非常感谢SqLFIDLE链接!现在我可以想办法了。顺便说一句,在SQL中“@”是什么意思?我以前从未见过它。它用于用户定义的变量。您可以在此处阅读更多关于它们的信息: