前言
本文主要记录SQL插入操作的相关笔记
一、插入多行数据
直接在values后添加多个括号,每个括号内加入每条记录。
代码如下(示例):
CREATE TABLE test1 (
id smallint(5) NOT NULL PRIMARY KEY,
first varchar(45) NOT NULL,
update_time DATETIME NOT NULL)
insert into test1 VALUEs
(1,'name1','2021-12-05'),
(2,'name2','2021-12-05')
输出:
1|name1|2021-12-05
2|name2|2021-12-05
注意输入的时候主键不能与已有主键重复
二、插入数据时已存在
在插入数据的时候发现主键冲突,要直接丢弃冲突的这行数据时,使用"ignore"关键字即可
代码如下(示例):
CREATE TABLE test1 (
id smallint(5) NOT NULL PRIMARY KEY,
first varchar(45) NOT NULL,
update_time DATETIME NOT NULL)
insert into test1 VALUEs(1,'name1','2021-12-05')
insert ignore into test1 VALUEs
(1,'name3','2021-12-05'),
(2,'name2','2021-12-05')
输出:
1|name1|2021-12-05
2|name2|2021-12-05
三、插入其他表中的数据
已知存在表table1,现在新建一个表table2,表1中有两个字段”id“与“str1”,表2中的字段与表1字段相同,现在需要将表1中id小于5的数据对应的str1添加到table2表中。代码如下:
方法一:
insert into table2
select null,str1 from table1 where id<5
方法二:
insert into table2(str1)
select str1 from table1 where id<5
四、覆盖一条记录如不存在就直接添加
已知存在表table1,表1中有两个字段”id“与“str1”,id为主键,现添加“2,‘aa’”记录到table1表中,如果已经存在id为2的主键,那么覆盖这条记录。代码如下:
方法一:
delete from table1 where id=2
insert into table1
value(2,'aa')
方法二:
repalce into table1
value(2,'aa')