|
web开发中,我们经常需要将一个表的数据插入到另外一个表,有时还需要指定导入字段,设置只需要导入目标表中不存在的记录,虽然这些都可以在程序中拆分成简单sql来实现,但是用一个sql的话,会节省大量代码。下面我以mysql数据库为例分情况一一说明:
两张表:insertTest和insertTest2,前者中有测试数据
create table insertTest(id int(4),name varchar(12));
insert into insertTest values(100,'liudehua');
insert into insertTest values(101,'zhourunfa');
insert into insertTest values(102,'zhouhuajian');
1.如果2张表的字段一致,并且希望插入全部数据,可以用这种方法:
INSERT INTO 目标表 SELECT * FROM 来源表;
insert into insertTest select * from insertTest2;
2.如果只希望导入指定字段,可以用这种方法:
INSERT INTO 目标表 (字段1, 字段2, ...) SELECT 字段1, 字段2, ... FROM 来源表;
注意字段的顺序必须一致。
insert into insertTest2(id) select id from insertTest2;
3.如果您需要只导入目标表中不存在的记录,可以使用这种方法:
INSERT INTO 目标表
(字段1, 字段2, ...)
SELECT 字段1, 字段2, ...
FROM 来源表
WHERE not exists (select * from 目标表
where 目标表.比较字段 = 来源表.比较字段);
1>.插入多条记录:
insert into insertTest2
(id,name)
select id,name
from insertTest
where not exists (select * from insertTest2
where insertTest2.id=insertTest.id);
或者
insert into `insertTest2` (email,username,password)
select email,username,password from `insertTest` where not ( username='admin' or username='100fuwu ); 2>.插入一条记录:
insert into insertTest
(id, name)
SELECT 100, 'liudehua'
FROM dual
WHERE not exists (select * from insertTest
where insertTest.id = 100);
使用 dual 作表名,select 语句后面直接跟上要插入的字段的值。
导入的时候出问题了:(
导出时的语句:
${MYSQL_HOME}/bin/mysql -upublic -ppublic -DMyDatabase -e"SELECT field1,field2,field3 INTO OUTFILE '/tmp/MyTable.temp
' FIELDS TERMINATED BY '#' FROM MyTable"
导入的语句:
${MYSQL_HOME}/bin/mysql -upublic -ppublic -DMyDatabase -e"LOAD DATA INFILE '/tmp/MyTable.temp' INTO TABLE MyTable(field1,field2,field3) FIELDS TER
MINATED BY '#'"
但是报错:
ERROR 1064 at line 1: You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near 'FIELDS TERMINATED BY '#'' at line 1
我觉得我的语法没有错误啊,大家帮忙给看看,谢谢!
又解决了:)
${MYSQL_HOME}/bin/mysql -upublic -ppublic -DMyDatabase -e"LOAD DATA INFILE '/tmp/MyTable.temp' INTO TABLE MyTable FIELDS TER
MINATED BY '#'"
(field1,field2,field3) |
|