如何在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+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告