如何形成MySQL条件插入?

为此,您可以使用MySQL双表插入。让我们创建一个表来了解条件条件插入的概念。创建表的查询如下-

mysql> create table ConditionalInsertDemo
   -> (
   -> UserId int,
   -> TotalUser int,
   -> NumberOfItems int
   -> );

使用insert命令在表中插入一些记录。查询如下-

mysql> insert into ConditionalInsertDemo values(101,560,780);

mysql> insert into ConditionalInsertDemo values(102,660,890);

mysql> insert into ConditionalInsertDemo values(103,450,50);

使用select语句显示表中的所有记录。查询如下-

mysql> select *from ConditionalInsertDemo;

输出结果

+--------+-----------+---------------+
| UserId | TotalUser | NumberOfItems |
+--------+-----------+---------------+
|    101 | 560       |           780 |
|    102 | 660       |           890 |
|    103 | 450       |            50 |
+--------+-----------+---------------+
3 rows in set (0.00 sec)

现在,表中有3条记录。您可以在对偶表的帮助下通过条件插入来插入下一条记录。只要用户表中不能存在UserId = 104和NumberOfItems = 3500,查询就会在表中插入记录。条件插入查询如下-

mysql> insert into ConditionalInsertDemo(UserId,TotalUser,NumberOfItems)
   -> select 104,900,3500 from dual
   -> WHERE NOT EXISTS (SELECT * FROM ConditionalInsertDemo
   -> where UserId=104 and NumberOfItems=3500);
Records: 1 Duplicates: 0 Warnings: 0

现在您可以检查表,是否插入记录。显示所有记录的查询如下-

mysql> select *from ConditionalInsertDemo;

输出结果

+--------+-----------+---------------+
| UserId | TotalUser | NumberOfItems |
+--------+-----------+---------------+
|    101 |       560 |           780 |
|    102 |       660 |           890 |
|    103 |       450 |            50 |
|    104 |       900 |          3500 |
+--------+-----------+---------------+
4 rows in set (0.00 sec)