6

I have a few column with UNIQUE INDEX. In some queries, duplicates should be acceptable, in which a postfix should be added to the value. For example, if test title exits, we change it to test title-2.

Is there a way to make a unique value upon DUPLICATE?

INSERT INTO table1
  (title, abr, name) 
  VALUES
  ('title', 'abr', 'name')

In this typical example, all three columns are UNIQUE. When the INSERT fails, I do not know which col caused the error to change its corresponding value.

How can I make a query to change value to value-identifier upon duplicate error?

2 Answers 2

3

I would agree with @BillThor that what you want to do may create some problems but what you need is ON DUPLICATE KEY UPDATE statement so your query would be something like this:

INSERT INTO table1
(`title`, `abr`, `name`) 
VALUES
('title', 'abr', 'name')
ON DUPLICATE KEY UPDATE `title` = CONCAT(`title`, '-2');

You can change CONCAT to any other function or your own stored procedure.

3
  • How should I know that the duplicate is on the column title? it can be from columns abr or name, which are also UNIQUE.
    – Googlebot
    Commented Nov 26, 2012 at 21:43
  • 1
    Use stored procedure which will check if given value already exists and in such case will return updated value so it will be something like ... ON DUPLICATE KEY UPDATE title = myTitleChecker(VALUES(title)), abr = myAbrChecker(VALUES(abr)), myNameChecker(VALUES(name)); Commented Nov 26, 2012 at 22:13
  • now it seems to be a practical solution!
    – Googlebot
    Commented Nov 27, 2012 at 0:23
4

I would look at your model first. Placing a unique key constraint on a non-unique column gets you into this kind of problem. What happens when you get a legitimate value like test title-2 but you've already used that value to resolve a collision on test title.

If I had to resolve your problem, I would build a query for each unique key of the form:

SELECT  title
FROM    table1
WHERE   title STARTS WITH ?

The results will need to be parsed to see what the suffix should be. It might be possible to do this in a stored procedure. However, I would strongly argue that the data model needed to be fixed, not the code.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.