tags:

views:

58

answers:

2

Using MySQL, when I have a table with (for example) three keys (one primary, auto-increment, and two uniques on a column, eg. 'code' and 'name'), how can I (efficiently) know which uniqueness constraint was violated when doing an insert?

You get an error #1062 - Duplicate entry 'Value' for key 2 , but how do I know key 2 is the key for the 'code' column and not the 'name' column?

We develop this application with multiple developers, and I want to prevent the day we don't add the constraints to a table in the same order, so the second key on my machine is the third key on another machine, and vice-versa.

Mapping to the exact column names involved is not really necessary, just to the key names is enough.

+1  A: 

As Bobby has suggested, SHOW indexes returns a resultset with relevant key index, check this page for further examples:

SHOW INDEXES FROM products_to_categories
WHERE Key_name = "PRIMARY"
AND Seq_in_index = '2';

+------------------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| Table                  | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |
+------------------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| products_to_categories |          0 | PRIMARY  |            2 | category_id | A         |           0 |     NULL | NULL   |      | BTREE      |         |
+------------------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+

However this will probably require as much code if not more than the following workaround.

Check which value you inserted collides with an existing row in the table:

SELECT code FROM myTable WHERE code = 'the_value_you_tried_to_insert';

or

SELECT name FROM myTable WHERE name = 'the_value_you_tried_to_insert';

Albeit not a very elegant solution.

Yannick M.
I re-asked the question on the MySQL mailing list, but got no answer, so this is the best answer. http://lists.mysql.com/mysql/219517
Jan Fabry
A: 

Maybe this helps:

SHOW INDEX FROM arbeit

Bobby

This will work, but would there be a more efficient way?
Jan Fabry
What do you mean by more efficient?
Yannick M.
Well, the most efficient way would be to have it in the error message, instead of just 'key 2'. I am a bit 'afraid' of your solution (like you said yourself), since it requires quite some code, and an extra database request.
Jan Fabry
Indeed, however if your applications allows, you could just keep an in memory catalog of the primary key indexes, query them once at startup, and just lookup the index of the errormessage in the catalog.
Yannick M.