![](/img/trans.png)
[英]Display rows with a specific ID from all tables in a database in PHP mysql
[英]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.