The implementation code in MySql that inserts data from one table into another
- 2020-05-17 06:47:17
- OfStack
This is what I wrote today when writing a table that imports data from one database into another
<?php
header("Content-type:text/html;charset=utf-8");
$conn = mysql_connect("localhost","root","");
mysql_select_db('nnd',$conn);
mysql_select_db('ahjk',$conn);
mysql_query("set names utf8");
$sql = mysql_query("select content,partid from phpcms_c_disease order by contentid desc limit
// So here's the data from the query And then loop in
$sql1= "INSERT INTO `nnd`.`demo`(content,parid) VALUES";
while($row = mysql_fetch_assoc($sql)){
$sql1.="('$row[content]','$row[partid]'),";
}
$sql1.=")";
$sql2 .= str_replace(",)",";",$sql1);
mysql_query($sql2);
?>
I didn't realize that I would write such rubbish code.
Here's a better way to do it
In the development of web, we often need to insert data from one table into another table, and sometimes we need to specify import fields, and only need to import records that do not exist in the target table. Although these can be separated into simple sql in the program, it will save a lot of code if we use one sql. Below, I take mysql database as an example to explain in case 11:
(id,name)
select id,name
from insertTest
where not exists (select * from insertTest2
where insertTest2.id=insertTest.id); 2 > Insert 1 record: insert into insertTest
(id, name)
SELECT 100, 'liudehua'
FROM dual
WHERE not exists (select * from insertTest
where insertTest.id = 100);