PHP/MySQL:将数据从旧数据库(没有 ID 的表)移动到新数据库(有 ID 的表)

我有一个函数可以将所有带有列的表从旧数据库获取到新数据库。到目前为止一切正常。现在我需要扩展该函数,以便在我的新数据库中的所有表中添加一个代理键(具有自动增量的主键 ID)。


旧数据库:


+-----------------------------------+------------+--------+

|               Col1                |    Col2    | NumCol |

+-----------------------------------+------------+--------+

| Value 1                           | Value 2    |    123 |

| This is a row with only one cell  |            |        |

| This row is testing html entities | Te<br />st |     45 |

+-----------------------------------+------------+--------+

新数据库:


+----+-----------------------------------+------------+--------+

| ID |               Col1                |    Col2    | NumCol |

+----+-----------------------------------+------------+--------+

|  1 | Value 1                           | Value 2    |    123 |

|  2 | This is a row with only one cell  |            |        |

|  3 | This row is testing html entities | Te<br />st |     45 |

+----+-----------------------------------+------------+--------+

如您所见,除了每个表中的新列 ID 之外,所有内容都保持不变。


这是我将旧数据库中的所有内容复制到新数据库的功能:


public function loadOldDBtoNewDB($oldDB,$newDB){

    $sqlshowTables = "SHOW TABLES ";

    $statement = $this->db->prepare($sqlshowTables);

    $statement->execute();

    $tables = $statement->fetchAll(PDO::FETCH_NUM);


    foreach($tables as $table){

        $sql[] = "INSERT INTO ".$newDB.".`".$table[0]."` SELECT * FROM ".$oldDB.".`".$table[0]."`; ";

    }


    $sqlState = implode(' ', $sql);

    $executeStatement = $this->db->exec($sqlState);


}

注意:运行此函数时,旧数据库和新数据库已经存在。


那么我需要如何更改我的插入语句,以便在每次插入期间添加一个 ID(自动增量)列?


哔哔one
浏览 148回答 2
2回答

紫衣仙女

您的新表应该已经AUTO_INCREMENT在id列上。然后NULL在执行选择时为其提供一个值!如果您的新表没有在ID列上设置自动增量,请添加ALTER TABLE `mytablename`&nbsp;CHANGE `ID` `ID` INT(11) NOT NULL AUTO_INCREMENT&nbsp;在您的NULL之前添加一个- 这将强制(首先出现在您的列列表中)使用,因为它不能是。*SELECTIDAUTO_INCREMENTNULL$sql[] = "INSERT INTO ".$newDB.".`".$table[0]."` SELECT NULL, * FROM ".$oldDB.".`".$table[0]."`; ";

眼眸繁星

您还可以使用以下命令创建新表create table new_table as (select * from old_table);alter table new_table add column id primary key auto_increment;
打开App,查看更多内容
随时随地看视频慕课网APP