In MySQL, can I copy one row to insert into the same table?

后端 未结 26 2297
-上瘾入骨i
-上瘾入骨i 2020-11-27 09:56
insert into table select * from table where primarykey=1

I just want to copy one row to insert into the same table (i.e., I want to duplicate an ex

26条回答
  •  攒了一身酷
    2020-11-27 10:25

    Just wanted to post my piece of PHP code, because I think the way I collect the columns is a bit cleaner in code than the previous examples. Also this shows how you could easily alter an field, in this case adding a string. But you could also replace a foreign key field with the newly added record, in case you want to copy some child records as well.

      // Read columns, unset the PK (always the first field in my case)
      $stmt = $conn->prepare('SHOW COLUMNS FROM template');
      $stmt->execute();
    
      $columns = $stmt->fetchAll();
      $columns = array_map(function ($element) { return $element['Field']; }, $columns);
    
      unset($columns[0]);
    
      // Insert record in the database. Add string COPY to the name field.
      $sql = "INSERT INTO `template` (".implode(",", $columns).")";
      if ($key = array_search('name', $columns))
          $columns[$key] = "CONCAT(name, ' COPY')";
      $sql .= " SELECT ".implode(",", $columns)." FROM `template` WHERE `id` = ".$id;
    
      $stmt = $conn->prepare($sql);
      $stmt->execute();
    

提交回复
热议问题