一般將同一個數據庫表的數據插入另一個表時,有兩種寫法:
第一種:這種寫法,是在不存在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')