PHP/MySQL:重建主键字段



问题:

主键字段'ID'

数据使用 REPLACE INTO 命令插入/更新到其中,该命令易于使用,但不幸的是增加了它所替换的记录的'ID'值。

所以我需要一种方法来完全重建ID字段,以便:

| ID  |  Name   |
|===============
| 21  |  deer   |
| 8   |  snow   |
| 3   |  tracks |
| 14  |  arrow  |

转到:

| ID |  Name   |
|===============
| 1  |  deer   |
| 2  |  snow   |
| 3  |  tracks |
| 4  |  arrow  |

我需要通过 php 来做到这一点。

当前尝试:

<?php
$reset = "SET @num := 0;
UPDATE `users` SET `ID` = @num := (@num+1);
ALTER TABLE `users` AUTO_INCREMENT =1;";
$con = mysql_connect("mysql2.000webhost.com","db_user","password");  
if (!$con)
{
     die('Could not connect: ' . mysql_error());
}
mysql_select_db("db_name", $con);
if (!mysql_query($reset,$con)) 
  {
    die('<h1>Nope:</h1>' . mysql_error());
  }
mysql_close($con);
?>

并尝试:

$reset = "ALTER TABLE `users` DROP `ID`;
ALTER TABLE `users` AUTO_INCREMENT = 1;
ALTER TABLE `users` ADD `ID` int UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;`";

也没有产生任何结果。

一切的束缚

我尝试的两个$reset命令都在MySQL中完美执行,但由于某种原因,它们无法从PHP中正确执行。


正如答案所指出的,@ 变量在每个连接中保留,因此运行多个查询是完全合理的:

///Trigger multiple queries
$nope = '<h1>Nope:</h1>  ';
$res1 = "SET @num := 0;";
$res2 = "UPDATE `users` SET `ID` = @num := (@num+1);";
$res3 = "ALTER TABLE `users` AUTO_INCREMENT =1;";
if (!mysql_query($res1,$con)) die($nope . mysql_error());
if (!mysql_query($res2,$con)) die($nope . mysql_error());
if (!mysql_query($res3,$con)) die($nope . mysql_error());
mysql_close($con);
mysql_*不支持

运行多个查询。您必须单独运行它们

  1. 如果您使用 INSERT INTO ... ON DUPLICATE KEY UPDATE ... ,您可以保留您的"ID"
function table2array ($table_name, $unique_col = 'id')
    {
$tmp=mysql_query("SELECT * FROM $table_name"); $count = mysql_num_rows($tmp);
while($rows[] = mysql_fetch_assoc($tmp));
array_pop($rows);
for ($c=0; $c < $count; $c++) 
{
  $array[$rows[$c][$unique_col]] = $rows[$c];
}
return $array;
    }
function reindexTable($table_name,$startFrom = 1) // simply call this function where you need a table to be reindexed!
    {
$array = table2array($table_name);
$id = 1; foreach ($array as $row) 
{
mysql_query("UPDATE `".$table_name."` SET `id` = '".$id."' WHERE `".$table_name."`.`id` = ".$row['id']);
$id++;
}
mysql_query("ALTER TABLE  `".$table_name."` AUTO_INCREMENT = ".$id);
    }

最新更新