【场景】:导入数据 【分类】:导出A表的某些数据插入到B表、自增ID

分析思路

难点:

1.导出A表的某些数据插入到B表

insert into table1(col1, col2,...,coln) select col1, col2,...,coln from table2

不写字段名,需要填充自增ID

  • [使用]:0或者null,自增id默认从1开始。
  • [使用]:或者没有在自增id中出现的(不重复)数(例如-1,-2),浮点型数据例如3.4,最后显示3,会进行四舍五入。即使定义了int类型,输入‘3’或者浮点型,都会强制转化为int类型,但是输入'a'会报错。具体细节可以看源码。

第一个字段id为什么可以写null? 示例中建表的时候写了id为自增id,而写0或者null或者没有在自增id中出现的(不重复)数(例如-1,-2),系统都会自动填充id。如果建表的时候没有写明是自增id,那么主键一定是不能为空的,这个时候写null就会报错。

按字段名填充,可以不录入id

  • [注意]:字段要与值一一对应。

其余注意事项:

  • 字段名可以省略,默认所有列;

  • 字段和值的个数必须一致。不能出现一行记录5个值,另外一行6个值的情况;

  • 如果写了字段,即使是空值也不能空着,用null代替;

扩展

前往查看:MySQL 插入语句

求解代码

方法一:

写字段名

#写字段,不需要插入id
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 year(submit_time) < 2021 
and score is not null

方法二:

不写字段名 + 自增id

#不写字段,自增id,用0或者null代替
insert into 
    exam_record_before_2021
select 0,uid,exam_id,start_time,submit_time,score
from exam_record
where year(submit_time) < 2021 
and score is not null