【问题标题】:mysql update or insert multiple records if not already exists in a table如果表中不存在mysql更新或插入多条记录
【发布时间】:2016-12-03 21:29:58
【问题描述】:

在 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);
}

【问题讨论】:

  • 您只是想用以前的数量更新现有项目的数量或添加旧的数量?
  • 您需要发出多个语句,因此请确保在事务(begincommit)中执行此操作以保持数据完整性。

标签: php mysql


【解决方案1】:

INSERT INTO ..... ON DUPLICATE KEY .... 是你的朋友。使用这种组合,您可以插入新记录或更新现有记录。为此,必须在定义您的行的字段上有一个唯一键,例如:product_category_id in your sample

*具有唯一键的表**

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>

【讨论】:

    【解决方案2】:

    在这里,您可以根据自己的要求使用以下任何一种。

    替换成

    如果记录在表上不可用,它会简单地插入,否则如果它已经可用,它将删除记录并插入新记录。

    REPLACE INTO table.inventory_item (product_category_id, quantity) SELECT '$quantity' ,'$pcid';
    

    重复密钥更新

    如果记录在表上不可用,它会简单地插入 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';
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-13
      • 1970-01-01
      • 2011-05-11
      相关资源
      最近更新 更多