一般将同一个数据库表的数据插入另一个表时,有两种写法:
第一种:这种写法,是在不存在target_table 的前提下,才可以使用。在插入时,先创建新表,在将数据插入:
语法:select * into target_table from source_table;
例如:select * into t_user_tem from t_user;
注意:mysql不支持此种写法,可以用:create table t_user_tem (select * from t_user);
第二种:这种写法,数据库中已经存在了表target_table目标表,只是将表source_table数据插入,插入的数据可以是source_table的一部分,也可以是整个表,根据需要进行变更。在使用此种写法时,也可以插入表source_table中不存在,而表target_table需要的数据,如:select 1,“奉佛”,column1 from source_table,当然了这些字段必需与target_table的字段相一致。
语法:insert into target_table(column1,column2) select column1,5 from source_table;
<span style="white-space:pre"> </span>insert into target_table (create_date,create_id,source_table_id,source_table_name...) select date,user_id ,id,name... from source_table ;
<span style="white-space:pre"> </span>insert into t_role_menu (role_id,menu_id) select 3,id from t_menu tm where tm.code LIKE '01%'
第三种:如果目标表中已经存在部分数据,而你要导入不存在的数据,可以试下此种写法;
语法:insert into target_table (column1,column2) select column1,column2 from source_table where not exists (select * from target-table where target_table.比较字段=source_table.比较字段)
如果两个表的字段完全一致:
insert into t_user_tem select * from t_user where not EXISTS(select * from t_user_tem where t_user_tem.id=t_user.ID)
如果只需插入部分字段:(插入多条数据)
insert into t_user_tem(id,user_name) select id,user_name from t_user where not exists (select * from t_user_tem where t_user_tem.user_name = t_user.user_name)
插入一条数据:
insert into t_user_tem (id,user_name) select 11,'petere' from DUAL where not exists (select * from t_user_tem where t_user_tem.user_name = 'petere')