主键字段为'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);
答案 0 :(得分:3)
mysql_*
不支持运行多个查询。你必须单独运行它们
答案 1 :(得分:1)
INSERT INTO ... ON DUPLICATE KEY UPDATE ...
,则可以保留“ID”答案 2 :(得分:0)
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);
}