且构网

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

防止MYSQL重复插入自动增量

更新时间:2023-01-22 16:22:39

您可以修改你的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

其中 $标签是标签(当然可以正确引用或作为占位符)如果尚未添加,则要添加。如果标签已经存在,这种方法甚至不会触发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.