如何形成 MySQL 条件插入?
mysqlmysqli database
为此,您可以使用 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)