如何形成一個 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)

更新於: 30-7-2019

2K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.