Don't ask why (as the answer is 'our totally weird and bepsoke setup...'), but I need to drop a unique key on a table (if it exists) without knowing the name of the key -- only the columns that make up the key.
e.g. I have this table
CREATE TABLE `my_table` (
`id` binary(36) NOT NULL,
`username` char(12) NOT NULL DEFAULT '',
`password` char(32) NOT NULL DEFAULT '',
`role` char(1) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username_2` (`username`,`role`),
UNIQUE KEY `username` (`username`),
UNIQUE KEY `username_3` (`username`),
UNIQUE KEY `username_4` (`username`),
)
and I'd like to drop the (username,role)
key but not the others (although only if it exists! - by the time I get to it, it might already have been dropped!)
Now I know how to drop a key when I know the constraint name
ALTER TABLE `my_table` DROP KEY `name_of_my_key`
and I know how to check if a unique key exists
SELECT EXISTS (SELECT constraint_name
FROM INFORMATION_SCHEMA.table_constraints
WHERE table_name = 'my_table' AND constraint_type='UNIQUE');
But this still doesn't help me when I only know the columns that make up the unique key.
Appreciate your help... Once I know a key exists, how can I derive the constraint_name(s) from only knowing which columns make up the constraint to allow me to drop them? Notice constraint name(s) because mySQL allows you to repeatedly add the same key like the 3 identical (username)
keys above.
The only things I've found are articles like Drop Foreign Key without knowing the name of the constraint? which only seem to show how you can get constraint names, not identify programmatically the constraints you want to drop.
Lastly if anyone knows why the hell mySQL would allow you to repeatedly add the same key (non-primary) to a table I'll be all ears. MySQL, you so crazy.