【发布时间】:2015-07-10 19:09:07
【问题描述】:
我有一个包含两个(相关)列的表:reference 和 count。我想做一个添加多个引用的查询,并执行以下操作:
- 如果我添加的引用不存在,请插入一个包含该引用及其计数的新行
- 如果表中已经存在我要添加的引用,请不要插入新行,只需增加此引用的计数即可。
我想过做这样的事情:
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)。
谢谢
【问题讨论】: