SQL基础语法—insert语句

insert语句

insert语句用于插入数据到表中,其基本语法有以下三种:

Syntax:
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
    [INTO] tbl_name
    [PARTITION (partition_name [, partition_name] ...)]
    [(col_name [, col_name] ...)]
    {VALUES | VALUE} (value_list) [, (value_list)] ...
    [ON DUPLICATE KEY UPDATE assignment_list]

INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
    [INTO] tbl_name
    [PARTITION (partition_name [, partition_name] ...)]
    SET assignment_list
    [ON DUPLICATE KEY UPDATE assignment_list]

INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
    [INTO] tbl_name
    [PARTITION (partition_name [, partition_name] ...)]
    [(col_name [, col_name] ...)]
    SELECT ...
    [ON DUPLICATE KEY UPDATE assignment_list]
  • 其中select...valuesinsert...set两种语句都是将指定的数据插入到现成的表中,而insert...select语句是将另外表中数据查出来并插入到现成的表中
  • partiion子句代表可以将数据插入到指定的表分区中
  • table_name代表将数据插入到的目标表
  • col_name 代表要插入指定数据的目标表列,如果是多列则用逗号隔开,如果目标表中的某些列没有在insert语句中指定,则这些列会插入默认值,当然可以使用default显式指定插入默认值
  • values中除了可以指定确定的数值之外,开可以使用表达式expr
insert into tbl_name (col1,col2) values(15,col1*2)  ##正确
insert into tbl_name (col1,col2) values(col1*2,15)  ##错误

案例演示:

## 修改sid字段,添加auto_increment属性
mysql> alter table students modify sid int auto_increment;
Query OK, 2 rows affected (0.23 sec)
Records: 2  Duplicates: 0  Warnings: 0

## 修改gender字段,添加默认值0
mysql> alter table students modify gender int default 0;
Query OK, 0 rows affected (0.08 sec)
Records: 0  Duplicates: 0  Warnings: 0

## 向students表中插入一条数据
mysql> insert into students(sname) values("bbb");
Query OK, 1 row affected (0.04 sec)

mysql> insert into students(sid,sname) values(5,"ccc");
Query OK, 1 row affected (0.02 sec)

mysql> insert into students(sname) values("ddd");
Query OK, 1 row affected (0.07 sec)

mysql> insert into students(sid,sname) values(4,"dd");
Query OK, 1 row affected (0.10 sec)

mysql> insert into students values(3*3,'fff',1);
Query OK, 1 row affected (0.09 sec)

mysql> select * from students;
+-----+--------+--------+
| sid | sname  | gender |
+-----+--------+--------+
|   1 | viktor |      1 |
|   2 | aaa    |   NULL |
|   3 | bbb    |      0 |
|   4 | dd     |      0 |
|   5 | ccc    |      0 |
|   6 | ddd    |      0 |
|   9 | fff    |      1 |
+-----+--------+--------+
7 rows in set (0.00 sec)
  • inset...values语句不光可以插入一条数据,也可以插入多条数据
insert into tbl_name(a,b,c) values(1,2,3)(4,5,6)
insert into students values(7,'abc'),(8,'bcd')
  • low_priority关键词代表如果有其他链接正在读取目标表数据,则此insert语句需要等待读取完成
  • low_priorityhigh_priority关键词仅在MylSAMMEMORYMERGE三种存储引擎下才生效
  • ignore关键词代表insert语句如果违反主键和伪意见的约束条件,则不报错而只产生警告信息,违反的行被丢弃,而不是整个语句回退;在数据类型转换有问题时如果有ignore则只产生警告信息,而不是语句回退
mysql> select * from students;
+-----+--------+--------+
| sid | sname  | gender |
+-----+--------+--------+
|   1 | viktor |      1 |
|   2 | aaa    |   NULL |
|   3 | bbb    |      0 |
|   4 | dd     |      0 |
|   5 | ccc    |      0 |
|   6 | ddd    |      0 |
|   9 | fff    |      1 |
+-----+--------+--------+
7 rows in set (0.00 sec)

mysql> insert ignore into students values(1,'aa',1),(7,'cc',0);
Query OK, 1 row affected, 1 warning (0.10 sec)
Records: 2  Duplicates: 1  Warnings: 1

insert... select语句

用于从另外的表中查出记录并插入到目标表中

insert into tbl_temp2(fld_id)
    select tbl_temp1.fld_order_id
    from tbl_temp1 where tbl_temp1.fld_order_id > 100;

当目标表和select语句中的表相同时,则会先将select语句的结果存放在临时表中,再插入到目标表中(注意执行顺序)

mysql> desc student2;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| sid   | int(11)     | NO   |     | NULL    |       |
| sname | varchar(20) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> desc students;
+--------+-------------+------+-----+---------+----------------+
| Field  | Type        | Null | Key | Default | Extra          |
+--------+-------------+------+-----+---------+----------------+
| sid    | int(11)     | NO   | PRI | NULL    | auto_increment |
| sname  | varchar(20) | NO   | UNI | NULL    |                |
| gender | int(11)     | YES  |     | 0       |                |
+--------+-------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

## concat用来合并两个字段
mysql> insert into student2(sid,sname) select sid,concat(sid,sname) from students where sid=1;
Query OK, 1 row affected (0.07 sec)
Records: 1  Duplicates: 0  Warnings: 0

## 当两个表中的字段不匹配时,插入会出现错误
mysql> insert into student2 select * from students;
ERROR 1136 (21S01): Column count doesn't match value count at row 1

##选定两个字段进行插入
mysql> insert into student2 select sid,sname from students;
Query OK, 8 rows affected (0.07 sec)
Records: 8  Duplicates: 0  Warnings: 0

mysql> select * from student2;
+-----+---------+
| sid | sname   |
+-----+---------+
|   1 | 1viktor |
|   2 | aaa     |
|   3 | bbb     |
|   7 | cc      |
|   5 | ccc     |
|   4 | dd      |
|   6 | ddd     |
|   9 | fff     |
|   1 | viktor  |
+-----+---------+
9 rows in set (0.00 sec)

insert on duplicate key update语句

当insert语句中使用on duplicate key update子句时,如果碰到当前插入的数据违反主键或唯一键的唯一性约束,则insert会转变成update语句修改对应的已经存在表中的这条数据。比如,如果a字段有唯一性约束且已经含有1这样的记录,则以下两条语句的执行结果相同。

insert into table(a,b,c) values(1,2,3)
    on duplicate key update c=c+1
update table set c=c+1 where a=1;

简而言之,该语句可以解决插入的数据与表之间的冲突。

案例演示:

mysql> insert into student2(sid,sname) select sid,sname from students where sid<3;
Query OK, 2 rows affected (0.08 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from student2;
+-----+--------+
| sid | sname  |
+-----+--------+
|   1 | viktor |
|   2 | aaa    |
+-----+--------+
2 rows in set (0.00 sec)

## 创建sname字段的unique索引
mysql> create unique index idx_1 on student2(sname);
Query OK, 0 rows affected (0.08 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc student2;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| sid   | int(11)     | NO   |     | NULL    |       |
| sname | varchar(20) | YES  | UNI | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.01 sec)

mysql> insert into student2(sid,sname) select sid,sname from students where sid=1;
ERROR 1062 (23000): Duplicate entry 'viktor' for key 'idx_1'
mysql> insert into student2(sid,sname) select sid,sname from students where sid=1 on duplicate key update sname='dabric';
Query OK, 2 rows affected (0.01 sec)
Records: 1  Duplicates: 1  Warnings: 0

mysql> select * from student2;
+-----+--------+
| sid | sname  |
+-----+--------+
|   1 | dabric |
|   2 | aaa    |
+-----+--------+
2 rows in set (0.00 sec)

mysql> insert into student values(1,'bb',0) on duplicate key update sname='b'sex=1;

练习

  • 将如下数据插入到dept表中
1,'computer science'; 2,'education'; 4,'accounting'
  • 根据create table...like语句创建teacher_backup表,并插入如下数据:
1,'susan'; 1; 2,'ruth'; 4; 3,'vivian', 4
  • 将teacher_backup表的数据通过insert...select语句插入到teacher表中

原文地址:https://www.cnblogs.com/dabric/p/12339644.html

时间: 2024-10-05 06:44:07

SQL基础语法—insert语句的相关文章

SQL基础语法—select语句

1 select语句介绍 select语句是值从现存的一个或多个表中查看满足条件的数据,其基本语法如下: Syntax: SELECT [ALL | DISTINCT | DISTINCTROW ] [HIGH_PRIORITY] [STRAIGHT_JOIN] [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT] [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS] select_expr [

SQL基础语法—update语句

1 update语句介绍 update语句用来修改表中的数据内容 Single-table syntax: UPDATE [LOW_PRIORITY] [IGNORE] table_reference SET assignment_list [WHERE where_condition] [ORDER BY ...] [LIMIT row_count] Multiple-table syntax: UPDATE [LOW_PRIORITY] [IGNORE] table_references S

SQL基础语法(笔记)

SQL基础语法:1.SELECT :SELECT 列名称 FROM 表名称 以及 SELECT * FROM 表名称2.DISTINCT:SELECT DISTINCT 列名称 FROM 表名称3.WHERE:SELECT 列名称 FROM 表名称 WHERE 列 运算符 值4.ORDER BY 语句用于根据指定的列对结果集进行排序.默认升序:ASC,降序:DESC5.INSERT:INSERT INTO table_name (列1, 列2,...) VALUES (值1, 值2,....),

SQL基础语法和函数

SQL常用查询语句和函数 (2012-05-09 09:44:55) 转载▼ 标签: sql查询 函数 sql常用语句 it 分类: SQL SQL SELECT 语法 SELECT 列名称 FROM 表名称 SELECT LastName,FirstName FROM Persons --------------------------------------------------------------------------------- SQL SELECT DISTINCT 语句 在

SQL基础语法等

--1.while循环 declare @sum int declare @i int set @i=1 set @sum=0 while(@i<101) begin set @sum =@sum+@i set @i=@i+1 if(@i>90) print @i end print @sum --2.goto语句 declare @num int set @num=100 flag: print @num select @num=@num+1 while(@num<106)goto f

Python基础语法&mdash;字符串&amp;语句&amp;集合

Python字符串 Python中不支持char单字符类型,单字符在Python中也是一个字符串 Python字符串更新 更新Python字符串方法 1234 var1 = 'Hello World!'print "Updated String :- ", var1[:6] + 'Python' 实际执行效果为 Updated String :- Hello Python Python转义字符 Python字符串运算符 Python字符串格式化 Python三引号(triple quo

SQL 基础:Select语句,各种join,union用法

一.基本的SELECT语句 1. “*”的注意事项:在SELECT语句中,用*来选取所有的列,这是一个应该抵制的习惯. 虽然节省了输入列名的时间,但是也意味着获得的数据比真正需要的数据多的多.相应的,也会降低应用程序的性能及网络性能. 良好的规则是只选所需. 2. join子句 join是用来定义如何从多个表中选取数据并组合成一个结果集. join必需是因为(1)我们所要获取的所有信息并不都在一个表中,或者(2)所要返回的信息都在一个表中,但是其上设置的条件信息却在另一个表中. join的共同点

JavaSE入门学习7:Java基础语法之语句(下)

继续接着Java基础语法来:JavaSE入门学习5:Java基础语法(一)和JavaSE入门学习6:Java基础语法(二). 语句 Java经常使用的3种循环:while.do...while,for. (5)Java循环语句之while 语法: watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" > 运行

SQL基础语法—create view语句

1 create view语句介绍 create view语句是将某个查询数据的定义保留下来,以便随时调用,这就是所谓的视图.视图本身不存储查询结果,只是一个定义. Syntax: CREATE [OR REPLACE] [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] [DEFINER = { user | CURRENT_USER }] [SQL SECURITY { DEFINER | INVOKER }] VIEW view_name [(col