如何在MySQL的INSERT INTO命令中使用WHERE子句?


在插入新行时,我们可以使用条件插入,即在INSERT INTO命令中使用WHERE子句。这可以通过以下几种方式完成:

使用虚拟表

在这种情况下,我们根据某些条件插入虚拟表中的值。语法如下:

INSERT INTO table_name(column1,column2,column3,…) Select value1,value2,value3,… From dual WHERE [conditional predicate];

示例

mysql> Create table testing(id int, item_name varchar(10));
Query OK, 0 rows affected (0.15 sec)

mysql> Insert into testing (id,item_name)Select 1,'Book' From Dual Where 1=1;
Query OK, 1 row affected (0.11 sec)
Records: 1 Duplicates: 0 Warnings: 0

mysql> Select * from testing;

+------+-----------+
| id   | item_name |
+------+-----------+
| 1    | Book      |
+------+-----------+

1 row in set (0.00 sec)

在上面的示例中,我们创建了一个名为“testing”的表,并使用虚拟表dual和一个条件向其中插入行。如果条件为真,MySQL将行插入表中,否则不插入。

使用具有相同结构的表

如果我们想插入到结构与另一个表相同的表中,那么下面的示例演示了如何进行条件插入,即如何在INSERT INTO语句中使用WHERE子句。

mysql> Insert into dummy1(id,name)select id, name from dummy Where id =1;
Query OK, 1 row affected (0.06 sec)
Records: 1 Duplicates: 0 Warnings: 0

mysql> select * from dummy;

+------+--------+
| id   | Name   |
+------+--------+
| 1    | Gaurav |
| 2    | Aarav |
+------+--------+

2 rows in set (0.00 sec)

mysql> select * from dummy1;

+------+--------+
| id   | Name   |
+------+--------+
| 1    | Gaurav |
+------+--------+

1 row in set (0.00 sec)

在上面的示例中,我们向名为“dummy1”的表中插入了值,该表与表“dummy”具有相同的结构,并且条件是只插入“id = 1”的行。

更新于:2020年6月20日

6K+ 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.