在 MySQL 中如何執行插入操作如果表為空?


您可以使用子查詢來執行插入操作,前提是表為空。為此,可以使用子查詢的 not exists 條件。

以下語法僅在您的表為空時有效。如果您的表不為空,則不會插入記錄。語法如下所示

INSERT INTO yourTableName(yourColumnName)
SELECT ‘anyValue’
WHERE NOT EXISTS (SELECT *FROM yourTableName);

為了理解上述語法,讓我們建立一個表。建立表的查詢如下所示

mysql> create table ExecuteInsertDemo
   -> (
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (0.67 sec)

讓我們使用 insert 命令在表中插入記錄。插入記錄的查詢如下所示

mysql> insert into ExecuteInsertDemo values('John');
Query OK, 1 row affected (0.19 sec)

假設我們的表不為空,它只有一條記錄。如果您執行 insert 命令,則 MySQL 不會將該記錄插入表中。

執行插入操作的查詢如下所示

mysql> insert into ExecuteInsertDemo(Name)
   -> select 'Larry'
   -> where not exists (select *from ExecuteInsertDemo);
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0

使用 select 語句顯示記錄。查詢如下所示

mysql> select *from ExecuteInsertDemo;

以下是輸出

+------+
| Name |
+------+
| John |
+------+
1 row in set (0.00 sec)

您需要從表中刪除記錄才能執行上面看到的查詢。使用 truncate 命令。查詢如下所示

mysql> truncate table ExecuteInsertDemo;
Query OK, 0 rows affected (1.10 sec)

執行以上查詢以執行插入命令。查詢如下所示

mysql> insert into ExecuteInsertDemo(Name)
   -> select 'Larry'
   -> where not exists (select *from ExecuteInsertDemo);
Query OK, 1 row affected (0.33 sec)
Records: 1 Duplicates: 0 Warnings: 0

使用 select 從表中顯示記錄。查詢如下所示

mysql> select *from ExecuteInsertDemo;

以下是輸出

+-------+
| Name  |
+-------+
| Larry |
+-------+
1 row in set (0.00 sec)

檢視示例輸出,當表為空時,“Larry”已成功插入。

更新於: 2019年7月30日

2K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告