如何形成一个 MySQL 条件插入?
为此,可以使用 MySQL 对偶表插入。让我们创建一个表来理解条件插入的概念。创建该表的查询如下所示 −
mysql> create table ConditionalInsertDemo -> ( -> UserId int, -> TotalUser int, -> NumberOfItems int -> ); Query OK, 0 rows affected (0.58 sec)
使用 insert 命令在表中插入一些记录。查询如下所示 −
mysql> insert into ConditionalInsertDemo values(101,560,780); Query OK, 1 row affected (0.19 sec) mysql> insert into ConditionalInsertDemo values(102,660,890); Query OK, 1 row affected (0.20 sec) mysql> insert into ConditionalInsertDemo values(103,450,50); Query OK, 1 row affected (0.15 sec)
使用 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); Query OK, 1 row affected (0.18 sec) 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)
广告