如下,假设某数据库里面有表a,a表里面有字段b

我的目的是修改字段b的值为数字序号,第一行是1,第二行是2,第n行是n,一直修改完所有记录,这条语句怎么写?

慕尼黑8549860
浏览 57回答 2
2回答

翻翻过去那场雪

如果表a有自增长ID的话就很好办了 update a set b = id 如果没的话写一个PHP的小程序就好<?php$con = mysql_connect("localhost","root","password") or die("数据库连接失败".mysql_error());//连接数据库mysql_select_db("test",$con) or die ("数据库选择失败".mysql_error());mysql_query("set names gbk");//设置编码格式$a = mysql_query("select * from a");$n = 1;while($b = mysql_fetch_array($a)){mysql_query("update a set b = "."'".$n."'"." where id = ".$b['id']); //where 后面的条件语句可以是任意该表内字段$n++;}

翻阅古今

将update语句放到for循环中如果是在数据库上操作,可以用T-SQL处理: eg: 表:ttt&nbsp;&nbsp;&nbsp;(id&nbsp;)有7条记录, id: 1 2 3 4 5 6 7 declare&nbsp;@i&nbsp;int&nbsp; set&nbsp;@i=7 while&nbsp;@i>0&nbsp;begin&nbsp; --insert&nbsp;into&nbsp;ttt&nbsp;values(@i) update&nbsp;ttt&nbsp;set&nbsp;id=@i+1&nbsp;where&nbsp;id=@i&nbsp; print&nbsp;@i set&nbsp;@i=@i-1 end go 一定要倒序循环 结果: id: 2 3 4 5 6 7 8 这样写:update&nbsp;ttt&nbsp;set&nbsp;id&nbsp;=&nbsp;id&nbsp;+1&nbsp;where&nbsp;id&nbsp;in&nbsp;(select&nbsp;id&nbsp;from&nbsp;ttt)&nbsp;也行 程序中在写sql&nbsp;的地方 可以套用for循环
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

MySQL