如何随机生成数据库中不存在的外键名称?

时间:2022-11-25 12:58:14

Suppose I am writing query like this.

假设我正在编写这样的查询。

SET foreign_key_checks = 0;

ALTER TABLE `StudentSubjectMarkMap` 
  ADD CONSTRAINT `here_I_want_some_random_name`
  FOREIGN KEY (`id` )
  REFERENCES `Subject` (`subjectId` )
  ON DELETE NO ACTION
  ON UPDATE NO ACTION
, ADD INDEX `here_I_want_some_random_name` (`id` ASC);

SET foreign_key_checks = 1;

My Question is "is it possible to generate some random String name as foreign key name?" I want such thing because this query is giving me duplicate key name error even after I dropped that key name.

我的问题是“是否可以生成一些随机字符串名称作为外键名称?”我想要这样的事情,因为即使在我删除了该键名后,这个查询也给了我重复的键名错误。

1 个解决方案

#1


2  

Index name is optional, so you don't need to specify it. In that case MySQL will assign a name for the index and it doesn't fail. See ALTER TABLE syntax for more details:

索引名称是可选的,因此您无需指定它。在这种情况下,MySQL将为索引指定一个名称,它不会失败。有关更多详细信息,请参阅ALTER TABLE语法:

ALTER [ONLINE | OFFLINE] [IGNORE] TABLE tbl_name
    [alter_specification [, alter_specification] ...]
    [partition_options]
  ADD {INDEX|KEY} [index_name]
        [index_type] (index_col_name,...) [index_option] ...
  ADD [CONSTRAINT [symbol]]
    FOREIGN KEY [index_name] (index_col_name,...)
    reference_definition

#1


2  

Index name is optional, so you don't need to specify it. In that case MySQL will assign a name for the index and it doesn't fail. See ALTER TABLE syntax for more details:

索引名称是可选的,因此您无需指定它。在这种情况下,MySQL将为索引指定一个名称,它不会失败。有关更多详细信息,请参阅ALTER TABLE语法:

ALTER [ONLINE | OFFLINE] [IGNORE] TABLE tbl_name
    [alter_specification [, alter_specification] ...]
    [partition_options]
  ADD {INDEX|KEY} [index_name]
        [index_type] (index_col_name,...) [index_option] ...
  ADD [CONSTRAINT [symbol]]
    FOREIGN KEY [index_name] (index_col_name,...)
    reference_definition