如何形成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)
热门推荐
6 足球队祝福语简短
10 朋友家住豪宅祝福语简短
11 浪漫的生日祝福语简短
12 比赛结束花束祝福语简短
13 最真的新春祝福语简短
14 修祖屋祝福语简短
15 早晨好正能量祝福语简短
16 初升高祝福语家长简短
17 婆婆生日祝福语短语简短
18 双节祝福语简短唯美