[英]mysql update or insert multiple records if not already exists in a table
mysql數據庫中有一個名為“ inventory_item”的表。 “ id”,“ product_id”和“ quantity”是表的列。 “ id”是主鍵,在插入記錄時自動生成。
當用戶提交要在表中插入多條記錄的表單時,可以在foreach循環中收集product_ids的所有數據及其數量。
因此,我需要同時插入多個記錄,並且僅當表中已經存在“ product_id”而不更新為新記錄時才更新數量。
這是我的代碼塊。
foreach ($dataArray as $value) {
$pcid = $value["pcid"];
$quantity = $value["quantity"];
$sql = "
UPDATE table.inventory_item
SET quantity='$quantity'
WHERE product_category_id='$pcid'
IF ROW_COUNT()=0
INSERT INTO table.inventory_item
(product_category_id, quantity)
VALUES ('$pcid', '$quantity')
";
$result = $conn->query($sql);
var_dump($result);
}
插入.....在重復鍵上 。 通過這種組合,您可以插入新記錄或更新現有記錄。 為此,有必要在一個字段上定義一個唯一鍵,例如: product_category_id
*具有唯一鍵的表**
CREATE TABLE `table` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`product_id` varchar(32) CHARACTER SET latin1 DEFAULT NULL,
`quantity` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `product_id` (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
樣品
mysql> select * from `table`;
Empty set (0,00 sec)
mysql> INSERT into `table` (product_id,quantity) Values ('p1',9),('p2',13) ON DUPLICATE KEY UPDATE quantity=VALUES(quantity);
Query OK, 2 rows affected (0,01 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> select * from `table`;
+----+------------+----------+
| id | product_id | quantity |
+----+------------+----------+
| 9 | p1 | 9 |
| 10 | p2 | 13 |
+----+------------+----------+
2 rows in set (0,00 sec)
mysql> INSERT into `table` (product_id,quantity) Values ('p3',9),('p2',15) ON DUPLICATE KEY UPDATE quantity=VALUES(quantity);
Query OK, 3 rows affected (0,00 sec)
Records: 2 Duplicates: 1 Warnings: 0
mysql> select * from `table`;
+----+------------+----------+
| id | product_id | quantity |
+----+------------+----------+
| 9 | p1 | 9 |
| 10 | p2 | 15 |
| 11 | p3 | 9 |
+----+------------+----------+
3 rows in set (0,00 sec)
mysql>
在這里,您可以根據需要使用以下任意一種。
更換成
如果記錄在表上尚不可用,它將簡單地插入其他內容,如果在表上尚不可用,則將刪除記錄並插入新記錄。
REPLACE INTO table.inventory_item (product_category_id, quantity) SELECT '$quantity' ,'$pcid';
重復鍵更新
如果該記錄在表上尚不可用,則只要在運行相應的update命令時已可用,則將簡單地插入else。
INSERT INTO table.inventory_item (product_category_id, quantity) VALUES ('$pcid', '$quantity')" ON DUPLICATE KEY UPDATE table.inventory_item SET quantity='$quantity' WHERE product_category_id='$pcid';
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.