首页 文章

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

提问于
浏览
2

在mysql数据库中有一个名为“inventory_item”的表 . “id”,“product_id”和“quantity”是表格的列 . “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);
}

2 回答

  • 2

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

    *一张带有独特钥匙**的 table

    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;
    

    Sample

    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>
    
  • 1

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

    REPLACE INTO

    如果该记录尚未在表上可用,则只需插入其他内容,如果它已经可用,则将删除该记录并插入新记录 .

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

    ON DUPLICATE KEY 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';
    

    希望这可以帮助 .

相关问题