简体   繁体   中英

MySQL drop unique key: needed in a foreign key constraint

Hello I`ve a table which look like this

CREATE TABLE `ratings` (
  `id` bigint NOT NULL,
  `profile_id` bigint NOT NULL,
  `stars` enum('1','2','3','4','5') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `email` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `token` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `deleted_at` timestamp NULL DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `survey_id` bigint DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `ratings_profile_id_email_unique` (`profile_id`,`email`),
  UNIQUE KEY `ratings_token_unique` (`token`),
  KEY `survey_id` (`survey_id`),
  CONSTRAINT `ratings_ibfk_1` FOREIGN KEY (`survey_id`) REFERENCES `surveys` (`id`),
  CONSTRAINT `ratings_profile_id_foreign` FOREIGN KEY (`profile_id`) REFERENCES `profiles` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

My goal is to delete the ratings_profile_id_email_unique key. I tried this statement

alter table ratings drop key ratings_profile_id_email_unique;

This produces: Cannot drop index 'ratings_profile_id_email_unique': needed in a foreign key constraint

What is wrong? How can a unique key needed in a fk constraint?

In SQL, in general, a foreign key constraint can refer to either a primary key or a unique key. MySQL extends this to any indexed column(s), but that is not relevant here.

Somewhere in your data model, you have a foreign key reference using these two keys instead of id . You need to fix such references in order to delete the index.

If you don't know where this is, you can use the information_schema tables, such as information_schema.referential_constraints and information_schema.key_column_usage .

For instance, this gets foreign key constraints that reference t :

select *
from information_schema.referential_constraints rc
where rc.referenced_table_name = 't'

(You may want to include the schema in them.) This is probably enough information, but if you need more key_column_usage can be more specific on the keys being used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM