douhua9726 2014-03-14 20:30
浏览 56
已采纳

MySQLi如果值不存在则插入

EDIT: I forgot to mention that my script should not input IF a row already exists in the new DB with the same column values, that is what I mean when I refer to "duplicate entries" despite there not being a common PK.

Here's my dilemma, I'm working with MySQLi to migrate data from an old table into a new table which have different designs and I want my program to be able to run multiple times without multiplying previous entries. My initial approach was to do a verification query for each inserted element:

//foreach elt of old table:
  $a = $old_table['a'];
  $b = $old_table['b'];
  $query = $db->query("SELECT `id` FROM `old_table` 
                       WHERE `a` = '$b' 
                       AND `b` LIKE '$b'")->fetch_assoc();
  if ($query == null) {
    //insert a row into the new table
  }

The problem with this method is that the run-time was horrendous and I managed to considerably cut it down by using a database transaction:

$query = $db->prepare("INSERT INTO  `new_table` 
          (`a`, `b`, `c`, `d`, `e`)
          VALUES (?, ?, ?, ?, ?)");
$query->bind_param('isssi', $a, $b, $c, $d, $e);
$db->query("START TRANSACTION");
foreach ($old_table as $old_row) {
  $a = $old_row['a'];
  ...
  $e = $old_row['e'];
  $query->execute();
}
$query->close();
$db->query("COMMIT");

The problem with this method is that it results in multiple entries if the program is run more then once. It's important to note that since both tables have different designs, there is no common Primary Key and therefore I don't think I can use DUPLICATE KEY.

Thoughts?

  • 写回答

3条回答 默认 最新

  • dougang1965 2014-03-17 13:15
    关注

    In fact, you already solved the problem, but for some reason stopped half-way.

    The problem with this method is that the run-time was horrendous and I managed to considerably cut it down by using a database transaction

    I wonder why didn't you include select into transaction as well.

    Thoughts?

    Just add select query you used to run in the first variant. That's all.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: