问题描述
我有一个非常简单的表,其中有3列tag_id, label, timestamp
,并且我需要尽可能轻量的查询,仅当列label
的值有了新值时才插入.
I have a very simple table with 3 columns tag_id, label, timestamp
and I need as lightweight as possible a query to insert only when there is a new value for the column label
.
我该如何编写sql查询来做到这一点?我已经在该网站上看到了一些示例,但是它们全都混在我无法理解的更复杂的查询中(有些涉及子查询).
How would I write an sql query to do this? I can see some examples already on the site but they are all mixed up in more complex queries (some involving subqueries) that I can't understand.
似乎有不同的处理方式,我需要找出最轻巧的方式,以便可以在循环中重复一次以一次插入多个标签,而又不会对服务器造成太大的压力.
There seems to be different ways of doing it and I need to find out the most lightweight one so that I can repeat it in a loop to insert multiple tags in one go without putting too much strain on the server.
推荐答案
您可以使用
ALTER TABLE `tableName` ADD UNIQUE KEY (label);
这将为架构中的该列强制一个唯一值.当您尝试插入重复的值时,您将得到一个错误.如果您只想忽略该错误,则可以使用INSERT IGNORE INTO
.
This will enforce a unique value for that column in the schema. You will get an error when you attempt to insert a duplicate value. If you want to simply ignore the error, you can use INSERT IGNORE INTO
.
这篇关于避免插入重复的列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!