MySQL如果一行或多行由于不存在而未更新,请插入它们[WHERE IN]


MySQL if one or more of the rows were not updated because they do not exist, insert them [ WHERE IN ]

我正在为我的网站创建一个类别系统,如果由于不存在而没有更新,我需要能够将一个类别插入到它的表中。

我的第一部分更新了WHERE in语句中定义的所有类别:

UPDATE `cat` SET `posts` = posts +1 WHERE cat IN ('category1', 'category2', 'idonotexist1', 'idonotexist2')

我如何让SQL有效地将任何由于不存在而无法更新的类别插入到表中?

具体地说,当你只做一次UPDATE时,我知道如何做到这一点,但使用WHERE IN,这对我来说有点复杂。我正在寻找将idonotexit1idonotexist2插入到表中的东西,因为它不存在。

我将提供所要求的所有信息。

首先,确保cat表中有一个唯一的索引:

alter table cat add unique index idx_cat(cat);

之后,对于列表中的每个类别,您可以执行以下操作:

insert into cat values('category1', 1)
on duplicate key update posts = posts + 1;