41

I have in my MYSQL table a unique key and i want to add to it.

UNIQUE KEY `user_id` (`user_id`,`account_id`)

and i want to add another

UNIQUE KEY `user_id` (`user_id`,`account_id`,`pet_id`)
yossi
  • 12,945
  • 28
  • 84
  • 110

3 Answers3

88
ALTER TABLE your_table 
   DROP INDEX user_id, 
   ADD UNIQUE KEY `user_id` (`user_id`,`account_id`,`pet_id`)
juergen d
  • 201,996
  • 37
  • 293
  • 362
  • 3
    Somewhat confusingly, the name of the unique key is in a separate namespace than the column name, so they can be same string but have totally separate meanings. (Stylistically, I prefer to pretend they're in the same namespace to avoid human assumption errors.) In case it's not obvious, you can split these statements apart into two `ALTER TABLE`s. – BaseZen Mar 16 '18 at 18:17
2

Drop the first key and then create the new one.

Jakob
  • 751
  • 4
  • 17
0

I use this code to change field 'uniq_key' which empty

UPDATE your_table  SET `uniq_key`= CONCAT(`user_id`, account_id, pet_id) WHERE  `uniq_key`= ''
dewaz
  • 137
  • 5