如果MySQL中的表为空,则执行INSERT吗?

如果表为空,则可以在子查询的帮助下执行插入。为此,使用子查询处理不存在的条件。

以下语法仅在表为空时才有效。如果您的表不为空,则不会插入记录。语法如下:

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

为了理解上述语法,让我们创建一个表。创建表的查询如下:

mysql> create table ExecuteInsertDemo
   -> (
   -> Name varchar(20)
   -> );

让我们使用insert命令在表中插入记录。插入记录的查询如下:

mysql> insert into ExecuteInsertDemo values('John');

假设我们的表格不为空。它只有一条记录。如果执行插入命令,则MySQL将不会在表中输入该记录。

执行插入的查询如下:

mysql> insert into ExecuteInsertDemo(Name)
   -> select 'Larry'
   -> where not exists (select *from ExecuteInsertDemo);
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;

运行以上查询以执行插入命令。查询如下:

mysql> insert into ExecuteInsertDemo(Name)
   -> select 'Larry'
   -> where not exists (select *from ExecuteInsertDemo);
Records: 1 Duplicates: 0 Warnings: 0

使用select在表中显示记录。查询如下:

mysql> select *from ExecuteInsertDemo;

以下是输出:

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

查看示例输出,该表为空时已成功插入“ Larry”。