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

标签 php mysql

我有一个函数,可以将所有表及其列从旧数据库转移到新数据库。到目前为止一切正常。现在我需要扩展该功能,以便在我的新数据库中的所有表中添加一个代理键(具有自动递增功能的主键 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(自动递增)列?

最佳答案

您的新表在 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]."`; ";

关于PHP/MySQL : Move data from old database (tables without an ID) to new database (tables with an ID),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56257416/

相关文章:

php - Zend Framework : Failed opening required Zend/Loader. php (include_path ='.:/php/includes')

php - 查询类似 Facebook 的新闻源的数据

python - 如何将此 SQL 语句转换为 Django QuerySet?

php - 如何在 MySQL 中插入带逗号的字符串?

mysql - 在mysql中批量插入不重复的两行值

mysql - 如何检索mysql中所有记录的树节点数?

php - 如何在 WordPress 中获取评论永久链接(使用 HTML anchor )?

php - MySQL PHP 查询问题

php - 空白多部分电子邮件

php - 关于MySQL存储查询的问题