mysql更新或插入多个记录(如果表中尚不存在)

时间:2016-12-03 07:28:54

标签: php mysql

有一个名为" inventory_item"在mysql数据库中。 " id"," product_id"和"数量"是表的列。 " ID"是主键并在插入记录时自动生成。

当用户提交要向表中插入多个记录的表单时,可以在foreach循环中收集product_id及其数量的所有数据。

因此我需要同时插入多个记录,并且只应更新数量,如果" 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);
}

1 个答案:

答案 0 :(得分:2)

INSERT INTO ..... ON DUPLICATE KEY .... 是你的朋友。使用此组合,您可以插入新记录或更新现有记录。为此,必须在字段上使用唯一键来定义您的行,如样本中的 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>