繁体   English   中英

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

[英]PHP/MySQL: Move data from old database (tables without an ID) to new database (tables with an ID)

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

旧DB:

+-----------------------------------+------------+--------+
|               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);

}

注意:当我运行此功能时,旧数据库和新数据库已经存在。

那么,如何更改我的inser语句,以便在每次插入过程中添加一个ID(自动递增)列?

您的新表在id列上应该已经有一个AUTO_INCREMENT 然后在执行选择时为其提供NULL值!

如果您的新表在ID列上未设置自动递增,则通过以下方式添加它

ALTER TABLE `mytablename` 
CHANGE `ID` `ID` INT(11) NOT NULL AUTO_INCREMENT 

SELECT*之前添加一个NULL这将强制ID (在列列表中最先出现)使用AUTO_INCREMENT ,因为它不能为NULL

$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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM