首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >按行号更新MySQL

按行号更新MySQL
EN

Stack Overflow用户
提问于 2013-08-28 21:58:31
回答 2查看 9.7K关注 0票数 2

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

代码语言:javascript
运行
复制
UPDATE cars SET idx = value WHERE row_number = i

我会在'for‘语句中这样做,我是语句的整数。所以我会更新语句中的每一行。

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-08-28 22:17:04

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

代码语言:javascript
运行
复制
/*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
);

在以下方面的成果:

代码语言:javascript
运行
复制
| ID |  A |
-----|----|--
|  1 | 10 |
|  2 |  5 |
|  3 | 12 |

如果你对此有任何疑问,请随便问。

另外,请注意其中的order by id。这很重要,因为在数据库中没有第一行或最后一行。理论上,如果没有order子句,每次都会有不同的结果。

您还可以看到它的在这里工作,住在广场上

票数 3
EN

Stack Overflow用户

发布于 2013-08-28 22:12:12

我不知道mysql的情况,但您可以在php中这样做

代码语言:javascript
运行
复制
$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);
    }
}

这将有效,只需根据您的使用修改此代码即可。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18498920

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档