Which unique key is hit with my insert?

冷暖自知 提交于 2020-01-05 10:10:12

问题


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:


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.




回答2:


Maybe this helps:

SHOW INDEX FROM arbeit

Bobby



来源:https://stackoverflow.com/questions/1486068/which-unique-key-is-hit-with-my-insert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!