簡體   English   中英

MySQL 刪除唯一鍵:在外鍵約束中需要

[英]MySQL drop unique key: needed in a foreign key constraint

你好,我有一張看起來像這樣的桌子

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

我的目標是刪除ratings_profile_id_email_unique鍵。 我試過這個說法

alter table ratings drop key ratings_profile_id_email_unique;

這會產生: Cannot drop index 'ratings_profile_id_email_unique': needed in a foreign key constraint

怎么了? fk 約束中如何需要唯一鍵?

在SQL中,一般來說,外鍵約束既可以指主鍵也可以指唯一鍵。 MySQL 將此擴展到任何索引列,但這與此處無關。

在您的數據 model 的某處,您有一個使用這兩個鍵而不是id的外鍵引用。 您需要修復此類引用才能刪除索引。

如果您不知道這是哪里,您可以使用information_schema表,例如information_schema.referential_constraintsinformation_schema.key_column_usage

例如,這會獲得引用t的外鍵約束:

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

(您可能希望在其中包含架構。)這可能是足夠的信息,但是如果您需要更多key_column_usage可以更具體地說明正在使用的鍵。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM