1

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.

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.

4
  • is the label a unique field? Commented Jun 11, 2013 at 10:53
  • label is just a char at the moment - should I set it as unique somewhere then? :) Commented Jun 11, 2013 at 10:53
  • 1
    you mean a string? just google for mysql unique Commented Jun 11, 2013 at 10:55
  • oh wow, so I just set a unique constraint to the column? wow ok.. Commented Jun 11, 2013 at 11:00

2 Answers 2

3

You can use

ALTER TABLE `tableName` ADD UNIQUE KEY (label);

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.

Sign up to request clarification or add additional context in comments.

Comments

-1

you can also use:

INSERT INTO table(`label`) VALUES ("new value") 
 ON DUPLICATE KEY UPDATE `label` = "new value";

1 Comment

This suggestion doesn't make any sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.