繁体   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