萬盛學電腦網

 萬盛學電腦網 >> 數據庫 >> mysql教程 >> MySQL中整條記錄復制並插入方法

MySQL中整條記錄復制並插入方法

MySQL中整條記錄復制並插入方法 大致方法是先查出所需要復制到記錄然後財插入,條件是兩個表的記錄結果數據類型都必須完全一樣才行哦。

從 MSSQL 中導出一個文章表,需要插入到 PHPCMS 中的內容表 phpcms_content 去,需要做到文章可以發布到不同的欄目中去。也就是說,需要復制一條記錄,並修改其 catid,再插入到表尾的位置上

 代碼如下 復制代碼

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'] .' 重復'.'<br/>';
   $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.'<br />';
   //$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.'<br />';
   //$result = $connector -> query($sql);
  }
  
 }
}

如果不需要插入,則更簡單:insert into mytable (select * from mytable where id=1) ON DUPLICATE KEY UPDATE id=2;

copyright © 萬盛學電腦網 all rights reserved