zoukankan      html  css  js  c++  java
  • 关于数据库id自动增长的问题

    关于数据库id自动增长的问题,一般来说,我们设置数据库的时候会把id设置成auto_increment(即自动增长的)。但是在我们插入数据后,再对其中的数据进行删除后,id就变得不连续了。那么我们怎么对有删除数据的数据使其重新按照id自动增长排序呢? 下面是一种PHP操作MySQL使得数据重新按照id自动增长的程序。
    <?php
    
    $hostname = "localhost";
    $database = "mydatabase";
    $username = "root";
    $password = "123456";
    $connect = mysql_pconnect($hostname, $username, $password) or trigger_error(mysql_error(),E_USER_ERROR); 
    
    $no = 1;
    
    function change_id($id)
    {
    	global $no; 
    
    	$sql = 'update my_table set id = ' . $no . ' where id = ' . $id;
    	mysql_query($sql);
    	$no = $no + 1;
    }
    
    mysql_select_db($database, $connect);
    $query_Record = "SELECT id FROM my_table ORDER BY id ASC";
    $all_Record = mysql_query($query_Record);
    $row_Record = mysql_fetch_assoc($all_Record);
    
    do {
    	change_id( $row_Record['id'] );
    } while ($row_Record = mysql_fetch_assoc($all_Record));
    
    // 重新设置id自增起点
    mysql_query('alter table my_bable AUTO_INCREMENT = ' . $no);
    
    echo 'ok';
    
    ?>
    要是还要更新其他的表,使得更新后的id对应,可在函数change_id中进行各种操作。  
  • 相关阅读:
    AWS EC2服务器的HTTPS负载均衡器配置过程
    大数据技术Hadoop笔试题
    网上找的hadoop面试题目及答案
    360全景图three.js
    360全景图three.js与Photo-Sphere-Viewer-master 3D全景浏览开发
    @font-face 字体
    scss语法
    6.事件
    5.回调函数
    4.querystring属性
  • 原文地址:https://www.cnblogs.com/gxldan/p/4066884.html
Copyright © 2011-2022 走看看