0

Is there a way to do it? Considering I have the following table:

 id | value
----|------
 1  | A
 2  | B

If I try to insert the values (1, "C") I get Integrity constraint violation: 1062 Duplicate entry '1' for key 'PRIMARY' as expected, considering id is a unique primary key. So, I tried using the following insert inside an AFTER INSERT ON trigger with the following insert syntax:

INSERT INTO table VALUES (NEW.id, NEW.value)
ON DUPLICATE KEY UPDATE NEW.id = NEW.id + 5000;

It removes the duplicate key error, but it just won't insert the duplicate one(s).

I made a procedure following Yogi's suggestion. This is what it looks like:

DELIMITER //
CREATE PROCEDURE set_keys(IN id INT, IN value char(1))
BEGIN
    DECLARE CONTINUE HANDLER FOR 1062
    SELECT concat('Duplicate keys detected: ',id,', ',value) AS msg;

    INSERT INTO tests (id, value) VALUES(id + 5000, value);
END;
//

Is doing CALL set_keys(NEW.id, NEW.value); from now on the proper way to do it?

2
  • isn't simpler to use an auto-increment key? P.s. consider that using ON DUPLICATE KEY UPDATE you don't insert the new row, simply edit the old one, so you 1-A becomes 5001-A and 1-C is lost Commented Oct 19, 2017 at 10:55
  • @RobertoBisello It would, but I'm importing data from another database, and can't modify the original one except for inserts. If the other database gives me 1-C, I should be able to insert it and keep both values from the column value. Commented Oct 19, 2017 at 11:00

1 Answer 1

1

Rather than directly performing INSERT INTO table,
You can perform this using PROCEDURE/FUNCTION.

Do exception handling for DUPLICATE KEY error under EXCEPTION block, increment the KEY column and RE_RUN the INSERT Statement again

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

5 Comments

Would making a function that does somethink like select count(*) from table where id = @id_to_insert and make an "if count = 1, add 5000" work? I'm sorry, I just don't know that much about mysql :/
@Newwt -- Only problem i see with your answer is, before every insert i will run one extra query, where as with exception handling, i will run extra query for duplicate records only...
I informed myself a little and -I think- I did what you suggested. Do you mind checking my edit on the question to see if I did it right? Thanks for the help so far!
@Newwt- Yes, Seems Correct to me. You need CONTINUE HANDLER, which you are using
I noticed just now if for example I try to insert an id of 1 without anything on the table, it inserts it directly as id + 5000, without there being a duplicate. What is causing it?

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.