1、目标表不存在:
create table 目标表名
as
select * from 表名 where 条件;
2、目标表存在:
insert into 目标表名
select * from 表名 where 条件;
举个例子:
在MySQL环境下,有old与new两个数据库,其中有表名为hr_staff_base的表,现需要将new库中表hr_staff_base 之于old库中相同表没有的数据从old的hr_staff_base表中插入,其中ID是主键:
insert into new.hr_staff_base
select * from old.hr_staff_base a
where a.project_id='bf280be9-b9ad-47a4-b610-23531ca28428'
and a.id not in
(select b.id from new.hr_staff_base b
where b.project_id='bf280be9-b9ad-47a4-b610-23531ca28428');
或者
insert into exam_record_before_2021(uid,exam_id,start_time,submit_time,score)
select uid,exam_id,start_time,submit_time,score
from exam_record where score is not null and date_format(start_time,'%Y')<'2021'
其中ID是自增的,这里可以选择不插入,会自动生成。
3、带更新的插入
注意这种原理是检测到主键或唯一性索引键重复就删除原记录后重新插入
REPLACE INTO table_name VALUES (value1, value2, ...)
例如:
现在有一套ID为9003的高难度SQL试卷,时长为一个半小时,请你将 2021-01-01 00:00:00 作为发布时间插入到试题信息表examination_info(其表结构如下图),不管该ID试卷是否存在,都要插入成功
replace into examination_info(exam_id,tag,difficulty,duration,release_time)
values (9003,'SQL','hard',90,'2021-01-01 00:00:00')
MySQL的跨库查询比较方便,直接如上图:数据库名+“.”+表名,Oracle可以用db links,而且子查询中加上必要的条件,能大大加快执行速度,如上例子中的子查询,不带where语句结果是一样的,但是执行起来更慢。在比如上面可以进一步优化:a.id not in 可以替换为 not exists,速度更快。
如:
……
and not exists
(select b.id from new.hr_staff_base b
where b.project_id='bf280be9-b9ad-47a4-b610-23531ca28428');
3、同一张表中将A的值赋给B:
update 表名 set A=B;
4、删除表:
truncate table 表名;