插入记录:
普通插入(全字段):insert into table_name values(value1,vaule2,...);
普通插入(限定字段):insert into table_name (col1,col2,...) values (value1,value2,...);
多条一次性插入:insert into table_name(col1,col2,...) values (value1_1,value1_2,...),(value2_1,value2_2,...),..;
从另一个表导入:insert into table_name select *from table_name1 [where key=value]
带更新的插入:replace into table_name select *from table_name1 [where key=value]
(检测主键或唯一性索引键重复就删除原记录后重新插入)
例1:
第一列为自增主键列,最后两列提交时间和得分可以为空,其他非空。
如果插入的表格存在自增主键,这意味着不需要自己手动填入,它会自动随表格行数进行自己增加
所以在插入数据的时候
方法一:指定插入的列名,不写id这一列的数据,让它自增
insert into exam_record(uid,exam_id,start_time,submit_time,score)
values (1001,9001,'2021-09-01 22:11:12','2021-09-01 23:01:12',90),
(1002,9002,'2021-09-04 07:01:02',null,null);
方法二:把id的值设置为null或者0,这样MYSQL会自己处理这个自增的id列
INSERT INTO exam_record VALUES
(NULL, 1001, 9001, '2021-09-01 22:11:12', '2021-09-01 23:01:12', 90),
(NULL, 1002, 9002, '2021-09-04 07:01:02', NULL, NULL);
方法三:直接填入id值,仅针对插入数据不多的时候使用
INSERT INTO exam_record VALUES
(NULL, 1001, 9001, '2021-09-01 22:11:12', '2021-09-01 23:01:12', 90),
(NULL, 1002, 9002, '2021-09-04 07:01:02', NULL, NULL);
例二:
新表exam_record_before_2021已经创建好,所以用insert into
第一列为自增键列,不能直接复制过去
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
例三:
replace into examination_info(exam_id,tag,difficulty,duration,release_time)
values (9003,'SQL','hard','90','2021-01-01 00:00:00');
更新记录:
update 表名 set 列名=. [where]
例1:
update examination_info set tag="Python" where tag="PYTHON"
例2:
update exam_record
set submit_time="2099-01-01 00:00:00",
score=0
where score is null and start_time<'2021-09-01';
删除记录
根据条件删除: delete from tb [where][order by][limit ]
全部删除:(表清空,包含自增计数器重置)truncate tb;
例一:
timestampdiff(interval,start,end)计算start和end的时间差,单位以指定的interval为准
常用可选:
second 秒
minutec分钟
hour 小时
day 天数
month 月数
year 年数
delete from exam_record
where timestampdiff(minute,start_time,submit_time)<5
and score<60;
例二:表同例一
delete from exam_record
where submit_time is null or timestampdiff(minute,start_time,submit_time)<5
order by start_time
limit 3;
需要删除的信息主要有三个筛选条件:
完成时间为空,完成时间与作答时间分钟差小于5,在以上信息的基础之上进行排序,作答时间在前3名。
执行顺序:from ,where,order by,limit,delete
例三:
truncate table exam_record;