且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

防止 MySQL 重复插入的自动增量

更新时间:2023-01-22 16:09:24

您可以将 INSERT 修改为如下所示:

You could modify your INSERT to be something like this:

INSERT INTO tablename (tag)
SELECT $tag
FROM tablename
WHERE NOT EXISTS(
    SELECT tag
    FROM tablename
    WHERE tag = $tag
)
LIMIT 1

其中 $tag 是您想要添加的标签(正确引用或作为占位符),如果它不存在的话.如果标签已经存在,这种方法甚至不会触发 INSERT(以及随后的自动增量浪费).您可能会想出比这更好的 SQL,但以上应该可以解决问题.

Where $tag is the tag (properly quoted or as a placeholder of course) that you want to add if it isn't already there. This approach won't even trigger an INSERT (and the subsequent autoincrement wastage) if the tag is already there. You could probably come up with nicer SQL than that but the above should do the trick.

如果您的表被正确索引,那么用于存在检查的额外 SELECT 将很快,并且数据库无论如何都必须执行该检查.

If your table is properly indexed then the extra SELECT for the existence check will be fast and the database is going to have to perform that check anyway.

尽管这种方法不适用于第一个标签.您可以使用一个您认为最终会一直使用的标签来为您的标签表设定种子,或者您可以单独检查一个空表.

This approach won't work for the first tag though. You could seed your tag table with a tag that you think will always end up being used or you could do a separate check for an empty table.