我有一个表,我想复制表中的特定行。我知道这不是最好的做事方式,但我们正在寻找快速解决方案。
这比我最初的想法更难,我需要做的就是将整个记录复制到MySql中自动增量表中的新记录,而无需指定每个字段。这是因为该表可能在将来发生变化,并可能会破坏重复。我将从PHP复制MySQL记录。
这是一个问题,因为在'SELECT *'查询中,MySql将尝试复制正在复制的记录的ID,这会产生重复的ID错误。
这封锁了:
INSERT INTO customer SELECT * FROM customer WHERE customerid=9181
。它还会阻止INSERT INTO customer (Field1, Field2, ...) SELECT Field1, Field2, ..... FROM customer WHERE customerid=9181.
有没有办法从PHP或MySQL做到这一点?
答案 0 :(得分:12)
我终于找到了这段代码。我相信它将来会帮助别人。所以就是这样。
function DuplicateMySQLRecord ($table, $id_field, $id) {
// load the original record into an array
$result = mysql_query("SELECT * FROM {$table} WHERE {$id_field}={$id}");
$original_record = mysql_fetch_assoc($result);
// insert the new record and get the new auto_increment id
mysql_query("INSERT INTO {$table} (`{$id_field}`) VALUES (NULL)");
$newid = mysql_insert_id();
// generate the query to update the new record with the previous values
$query = "UPDATE {$table} SET ";
foreach ($original_record as $key => $value) {
if ($key != $id_field) {
$query .= '`'.$key.'` = "'.str_replace('"','\"',$value).'", ';
}
}
$query = substr($query,0,strlen($query)-2); # lop off the extra trailing comma
$query .= " WHERE {$id_field}={$newid}";
mysql_query($query);
// return the new id
return $newid;
}
以下是文章http://www.epigroove.com/posts/79/how_to_duplicate_a_record_in_mysql_using_php
的链接答案 1 :(得分:1)
怎么样?
insert into test.abc select null, val1, val2 from test.abc where val2 = some_condition;
似乎对我有用。当然,替换你的桌子,田地,条件。
null让DB为您生成自动增量ID。
答案 2 :(得分:1)
选项:
避免使用*
通配符,并自行指定所有列。但是你说这个表预计将来会改变,这对你的案子来说不是一个可行的解决方案。
从当前表定义中查找列(使用DESCRIBE
或查询INFORMATION_SCHEMA.COLUMNS
)。使用有关元数据的信息来构建查询,省略自动增量主键列。
执行SELECT *
查询,将行提取回应用程序,然后从中删除自动增量列。然后使用该元组构造INSERT
语句。
简而言之,您需要适应不断变化的元数据。这可能无法在单个查询中完成。
答案 3 :(得分:0)
如何将行复制到临时表中,然后再将其复制到客户表中?我认为这会强制mysql给它一个新的自动增量ID,尤其是你发布的查询的第二个版本。
答案 4 :(得分:0)
到目前为止有两个帖子,这里是第三个选项:在PHP中,动态确定表格中的字段。或者,您可以创建一个“硬编码”字段的数组列表,手动维护以反映表格。生成的查询不会使用*。
答案 5 :(得分:0)
如果您知道表中主键列的名称(我猜你这样做,因为它仍然在where子句中),我认为你可以这样做:
编辑 - 我忘了MySQL不支持select ... into。这应该工作
create new_table
select *
from customer
where customerid = 9181
alter table new_table
drop column customerid
insert into customer
select null, *
from new_table
drop table new_table
答案 6 :(得分:0)
有一个简单的方法,可以在同一表测试中创建重复记录。在我的本地