当前位置:首页 > PHP教程 > PHP总结归纳

MySQL如何复制表中的一条记录并插入

先把需求说一下吧。从 mssql 中导出一个文章表,需要插入到 phpcms 中的内容表 phpcms_content 去,需要做到文章可以发布到不同的栏目中去。也就是说,需要复制一条记录,并修改其 catid,再插入到表尾的位置上。 mysql 复制一条数据并插入的语句: insert i

先把需求说一下吧。从 mssql 中导出一个文章表,需要插入到 phpcms 中的内容表 phpcms_content 去,需要做到文章可以发布到不同的栏目中去。也就是说,需要复制一条记录,并修改其 catid,再插入到表尾的位置上。

mysql 复制一条数据并插入的语句:

insert into phpcms_content (select ".$r[$i]['aid']." + 520, ".$r[$i]['cateid'].", news_catid, catid, typeid, areaid, title, style, thumb, keywords, keywords, posids, url, listorder, status, userid, username, inputtime, updatetime, searchid, islink, prefix from phpcms_content where contentid = '".$r[$i-1]['aid']."')

大致为:insert into a select id+1, ...(其它字段) from a ;

下面php具体程序:

$query = "select * from articleincategory order by articleid "; $result = $connector -> query($query); $i = 0; while($myrow = $connector -> fetch_array($result)) { $r[$i]['aid'] = $myrow["articleid"]; $r[$i]['cateid'] = $myrow["categoryid"]; $i++; } for($i = 0; $i < count($r); $i++) { if($i > 0) { if( $r[$i]['aid'] == $r[$i-1]['aid'] ) { echo '第 '. $i. ' 条数据 '. $r[$i]['aid'] .' 与前一条数据 '. $r[$i-1]['aid'] .' 重复'.' '; $sql = " insert into phpcms_content (select ".$r[$i]['aid']." + 520, ".$r[$i]['cateid'].", news_catid, catid, typeid, areaid, title, style, thumb, keywords, keywords, posids, url, listorder, status, userid, username, inputtime, updatetime, searchid, islink, prefix from phpcms_content where contentid = '".$r[$i-1]['aid']."') "; //$sql = " insert into phpcms_c_news (select ".$r[$i]['aid']." + 520, template, titleintact, content, groupids_view, readpoint, author, copyfrom, paginationtype, maxcharperpage, sub_title from phpcms_c_news where contentid = '".$r[$i-1]['aid']."') "; echo $sql.' '; //$result = $connector -> query($sql); //insert into test (select id + 10, name, class, score from test where id = '1'); } else if( $r[$i]['aid'] != $r[$i-1]['aid'] ) { $sql = " update phpcms_content set origin_cateid = '".$r[$i]['cateid']."' where contentid = '".$r[$i]['aid']."' "; echo $sql.' '; //$result = $connector -> query($sql); } } }

如果不需要插入,则更简单:insert into mytable (select * from mytable where id=1) on duplicate key update id=2;

或者: update mytable set id=2 where id=1;

.syntaxhighlighter{padding-top:20px;padding-bottom:20px;}

【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!