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 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题