【问题标题】:Adding multiple rows and catching non inserted ones添加多行并捕获未插入的行
【发布时间】:2015-07-10 19:09:07
【问题描述】:

我有一个包含两个(相关)列的表:referencecount。我想做一个添加多个引用的查询,并执行以下操作:

  • 如果我添加的引用不存在,请插入一个包含该引用及其计数的新行
  • 如果表中已经存在我要添加的引用,请不要插入新行,只需增加此引用的计数即可。

我想过做这样的事情:

INSERT IGNORE INTO table (reference, count) VALUES ($ref1, $newquantity1), ($ref2, $newquantity2), ($ref3, $newquantity3) //etcaetera 

// Here I'd catch the ignored rows ( = the references that are already in the table)

UPDATE table
SET count = CASE reference 
   WHEN '.$reference_already_present_1.' THEN 'count = count + '.$newquantity1.'
   WHEN '.$reference_already_present_2.' THEN 'count = count + '.$newquantity2.'
    //and so on for every reference already in the table
END
WHERE reference IN($reference_already_present_1, $reference_already_present_2);

(此更新查询来自here

问题是,我不知道是否可以从第一次插入中捕获被忽略的行,如果可以,该怎么做。有可能吗?

如果没有,我还能如何实现我所需要的?

(如果有任何相关,我正在使用 php、pdo 和 mysql)。

谢谢

【问题讨论】:

    标签: mysql pdo


    【解决方案1】:

    你想要insert . . . on duplicate key update。但首先,您需要一个唯一索引:

    create unique index idx_table_reference on table(reference);
    
    insert into table(reference, count)
        values($reference, $count)
        on duplicate key update count = count + values(count);
    

    【讨论】:

    • 谢谢。可以肯定的是,最后一行不应该是on duplicate key update count = count + values(**$**count); 吗?
    • @Malimalo 。 . .您可以使用count = count + $countcount = count + values(count)values() 函数返回更新中使用的字段的值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    • 2019-05-25
    • 2013-01-13
    相关资源
    最近更新 更多