【发布时间】:2016-11-27 08:00:23
【问题描述】:
我有几个数据文件,如下所示:
- table 1 - table 2 - table 3
id val id val id val
============ ========== ===========
1 one 1 uno 1 un
2 two 4 dos 6 deux
3 three 5 tres 7 trois
我正在尝试将它们插入到期望的数据库中:
= result table
id val
============
1 one
2 two
3 three
d1 uno
4 dos
5 tres
dd1 un
6 deux
7 trois
数据库结构为:
= sqlite database file: data.db
CREATE TABLE register (
id VARCHAR(3) PRIMARY KEY,
val VARCHAR(16)
);
我想出了这种解决方案:
<?php
$table1 = array("1"=>"one","2"=>"two","3"=>"three");
$table2 = array("1"=>"uno","4"=>"dos","5"=>"tres");
$table3 = array("1"=>"un","6"=>"deux","7"=>"trois");
$fileHandle = new PDO("sqlite:data.db");
$fileHandle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
foreach($table1 as $key => $value){
try{
$fileHandle->exec("INSERT INTO `register` (id,val) VALUES ('".$key."', '".$value."');");
}catch(PDOException $e){
if($e->getCode()=='23000'){ // if key exists, add a "d" to differentiate
$fileHandle->exec("INSERT INTO `register` (id,val) VALUES ('d".$key."', '".$value."');");
}
}
}
// keys: 1, 2, 3
foreach($table2 as $key => $value){
try{
$fileHandle->exec("INSERT INTO `register` (id,val) VALUES ('".$key."','".$value."');");
}catch(PDOException $e){
if($e->getCode()=='23000'){ // if key exists, add a "d" to differentiate
$fileHandle->exec("INSERT INTO `register` (id,val) VALUES ('d".$key."', '".$value."');");
}
}
}
// keys: 1, 2, 3, d1, 4, 5
foreach($table3 as $key => $value){
try{
$fileHandle->exec("INSERT INTO `register` (id,val) VALUES ('".$key."', '".$value."');");
}catch(PDOException $e){
echo " getCode : ".$e->getMessage()."\n";
if($e->getCode()=='23000'){ // if key exists, add a "d" to differentiate
$fileHandle->exec("INSERT INTO `register` (id,val) VALUES ('d".$key."', '".$value."');");
}
}
}
// Signals error on the INSERT in the CATCH body
?>
但是在第二次出现时卡住了。在示例中生成重复键 (d1)。
SQLSTATE[23000]: Integrity constraint violation: 19 UNIQUE constraint failed: register.id
我可以看到重复的模式,但我不知道如何压缩它。否则重新尝试修改的密钥。
提前感谢您的意见。
【问题讨论】:
-
试图集中我的问题。任何结构都不能更改;数据和数据库已经存在(有数千条记录)。目标是通过添加一些更改来插入重复的 ID(约束阻止)。因此,如果我们有三个记录,它们的 ID 相同,分别为 1、1、1,它们将作为 1、d1、dd1 插入数据库。