- 单条插入
INSERT INTO `test`.`exam_record_before_2021`
VALUES
( 6, 1001, 9002, '2020-01-02 09:01:01', '2020-01-02 09:21:01', 70 );
- 多条插入
INSERT INTO `test`.`exam_record_before_2021` ( `id`, `uid`, `exam_id`, `start_time`, `submit_time`, `score` )
VALUES
( 2, 1001, 9002, '2020-01-02 09:01:01', '2020-01-02 09:21:01', 70 );
- 全表复制
INSERT INTO exam_record_before_2021 SELECT
*
FROM
exam_record
WHERE
YEAR ( start_time ) < "2021"
AND score IS NOT NULL
- 表部分字段复制
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 ( start_time ) < "2021"
AND score IS NOT NULL
)
- 带更新的插入
这种原理是检测到主键或唯一性索引键重复就删除原记录后重新插入
REPLACE INTO `test`.`examination_info` ( `exam_id`, `tag`, `difficulty`, `duration`, `release_time` )
VALUES
( 9003, 'SQL', 'hard', 90, '2021-01-01 00:00:00' );
掌握replace into···values的用法
replace into 跟 insert into功能类似,不同点在于:replace into 首先尝试插入数据到表中,
如果发现表中已经有此行数据(根据主键或者唯一索引判断)则先删除此行数据,然后插入新的数据;
否则,直接插入新数据。
要注意的是:插入数据的表必须有主键或者是唯一索引!否则的话,replace into 会直接插入数据,这将导致表中出现重复的数据。