MySQL之插入数据

MySQL 刘宇帅 4年前 阅读量: 826

插入 students 表一条数据包含所有字段的值

insert into students values (1,'0001','洛基',2,25,'2019-12-20 20:00:00','2019-12-20 20:00:00');

执行

mysql> insert into students values (1,'0001','洛基',2,25,'2019-12-20 20:00:00','2019-12-20 20:00:00');
Query OK, 1 row affected (0.00 sec)

一次插入多条数据包含所有字段的值到 mysql

insert into students values (2,'0002','冷锋',2,25,'2019-12-20 20:00:00','2019-12-20 20:00:00'),(3,'0003','六一',2,25,'2019-12-20 20:00:00','2019-12-20 20:00:00');

执行

mysql> insert into students values (2,'0002','冷锋',2,25,'2019-12-20 20:00:00','2019-12-20 20:00:00'),(3,'0003','六一',2,25,'2019-12-20 20:00:00','2019-12-20 20:00:00');
Query OK, 2 rows affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0

students 表中 id 是自增的,created_at、updated_at 也是可取默认值的,所以在实际使用中我们经常需要插入指定字段的数据到数据库

insert into students (`no`,`name`,`sex`,`age`) values ('0004','杨过',2,25);

执行

mysql> insert into students (`no`,`name`,`sex`,`age`) values ('0004','杨过',2,25);
Query OK, 1 row affected (0.00 sec)

查看数据库最后结果

mysql> select * from students;
+----+------+--------+-----+------+---------------------+---------------------+
| id | no   | name   | sex | age  | created_at          | updated_at          |
+----+------+--------+-----+------+---------------------+---------------------+
|  1 | 0001 | 洛基   |   2 |   25 | 2019-12-20 20:00:00 | 2019-12-20 20:00:00 |
|  2 | 0002 | 冷锋   |   2 |   25 | 2019-12-20 20:00:00 | 2019-12-20 20:00:00 |
|  3 | 0003 | 六一   |   2 |   25 | 2019-12-20 20:00:00 | 2019-12-20 20:00:00 |
|  4 | 0004 | 杨过   |   2 |   25 | 2019-12-20 00:26:14 | NULL                |
+----+------+--------+-----+------+---------------------+---------------------+
4 rows in set (0.00 sec)

其他插入语句

不存在时插入,存在时先删除再添加

replace into students values (1,'0001','洛基',2,24,'2019-12-20 20:00:00','2019-12-20 20:00:00');

我们执行会发现返回的 affect rows 是 2

mysql> replace into students values (1,'0001','洛基',2,24,'2019-12-20 20:00:00','2019-12-20 20:00:00');
Query OK, 2 rows affected (0.07 sec)

不存在时插入,存在则忽略

insert ignore into students values (1,'0001','洛基',1,23,'2019-12-20 20:00:00','2019-12-20 20:00:00');

我们执行可看到 affected rows 是 0

mysql> insert ignore into students values (1,'0001','洛基',1,23,'2019-12-20 20:00:00','2019-12-20 20:00:00');
Query OK, 0 rows affected, 1 warning (0.00 sec)

不存在添加,已存在更新

insert into students values (1,'0001','洛基',1,23,'2019-12-20 20:00:00','2019-12-20 20:00:00') on duplicate key update age=79;

执行如下

mysql> insert into students values (1,'0001','洛基',1,23,'2019-12-20 20:00:00','2019-12-20 20:00:00') on duplicate key update age=79;
Query OK, 2 rows affected (0.01 sec)

如上执行返回的 affected rows 也是 2,原因目前不可知,待深入学习。。

提示

功能待开通!


暂无评论~