用mysql 怎样把表的 id字段的记录改为 1,2,3递增?
如原来是
+---------+
|    id   |
+---------+
|      24 |
+---------+
|      23 |
+---------+
|      53 | 
+---------+
|      98 |
+---------+
改成
+---------+
|    id   |
+---------+
|      1  |
+---------+
|      2  |
+---------+
|      3  | 
+---------+
|      4  |
+---------+
怎么写这个update,用循环?

解决方案 »

  1.   

    mysql不知道.sql 2000/2005
    update tb set id = (select count(1) from tb where id < t.id) + 1 from tb t
      

  2.   

    ;with t as
    (
    select row_id=row_number over(order by id),* from tb
    )
    update tb set id=row_id
      

  3.   

    http://forum.csdn.net/SList/MySQLPostgresql/
      

  4.   

    update tb set id = (select count(1) from tb where id < t.id) + 1 from tb t
    我用 mysql 试了一下,报错,怎么修改一下? 另外这个逻辑我也看不太懂,比较菜
    (select count(1) from tb where id < t.id) + 1
      

  5.   

    参考下贴http://blog.csdn.net/ACMAIN_CHM/archive/2009/04/20/4095531.aspx
      

  6.   


    先想办法桉贴子中的方法得到下面结果,然后再做 update aa ,(select ......) b set aa.id=b.sno where aa.id=bb.id
    +---------+---------+
    |    id   |    sno  |
    +---------+---------+
    |      24 |      1  |
    +---------+---------+
    |      23 |      2  |
    +---------+---------+
    |      53 |      3  |  
    +---------+---------+
    |      98 |      4  |
    +---------+---------+
      

  7.   

    而且这一帖中的这个查询,没实现rownum 递增呀?
    mysql> select @x:=ifnull(@x,0)+1 as rownum,id,col
        -> from tbl
        -> order by col;
    +--------+----+------+
    | rownum | id | col  |
    +--------+----+------+
    |      1 |  1 |   26 |
    |      1 |  3 |   35 |
    |      1 |  2 |   46 |
    |      1 |  4 |   68 |
    |      1 |  6 |   92 |
    |      1 |  5 |   93 |
    +--------+----+------+应该这样查询才会递增
    set @rownum=0;
    select @rownum := @rownum+1 as rownum, id from user11; 
      

  8.   

    多谢,终于实现了。set @rownum=0;select @rownum := @rownum+1 as rownum, id from user11;update user11 a, (select @rownum := @rownum+1 as rownum, id from user11) b set a.id=b.rownum where a.id=b.id; ------------
    两张表连起来update我还是第一次写。sql写得比较少。
    使用联接查询(笛卡尔积)/子查询 看着挺晕的,刚才没细琢磨。我也是才看那篇文章,没想到提问时就遇到作者了,还真巧。ACMAIN_CHM 你的头像是老狼吗?看着还挺剽悍,我刚才看你的文章时想。>_< 。
      

  9.   

    但C/S如果connection一直保持则要考虑 set @x=0
    意思是
    但C/S如果connection一只保持则要考虑先 set @x=0
    -------
    还有那个“再次查询的时候需要初始化”我也不太明白。我用的是mysql querybrower,是C/S链接吧?
    我又搜到关于 变量 的描述:
    对于使用select语句为变量赋值的情况,若返回多条记录,则变量的值为最后一条记录的值,不过不建议在这种情况下使用;若返回结果为空,即没有记录,此时变量的值为上一次变量赋值时的值,如果没有对变量赋过值,则为NULL。
    则变量的值为最后一条记录的值的话,@x 的二次就应该是1而不是null了,为什么那些rownum最后都是1呢?
      

  10.   

    where a.col>=b.col 或 where a.col>=b.col 或 where col<=a.col
     看着还是比较抽象。
      

  11.   

    如果是做的主键的话,用auto_increment,再把起始值设置为1就行了。