表中的重复键用于sql中的外键

时间:2016-07-30 07:43:02

标签: mysql sql-server foreign-key-relationship

我使用mysql_workbench创建数据库我有products_typescategoriessubcategories表。 category_idsubcategory_id分别是引用categoriessubcategories表的外键。当我forward engineer这个模型从workbenchmysql database on phpMyAdmin时,它会给出错误

Can't write; duplicate key in table 'product_types'

这是确切的代码以及错误。

Executing SQL script in server
ERROR: Error 1022: Can't write; duplicate key in table 'product_types'
SQL Code:
        -- -----------------------------------------------------
        -- Table `argo_project_01_2`.`product_types`
        -- -----------------------------------------------------
        CREATE TABLE IF NOT EXISTS `argo_project_01_2`.`product_types` (
          `id` INT NOT NULL,
          `category_id` INT NULL,
          `subcategory_id` INT NULL,
          `title` VARCHAR(100) NULL,
          `description` TEXT NULL,
          `status` INT NULL DEFAULT 0,
          `created` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
          `modified` TIMESTAMP NULL,
          PRIMARY KEY (`id`),
          INDEX `category_id_idx` (`category_id` ASC),
          INDEX `subcategory_id_idx` (`subcategory_id` ASC),
          CONSTRAINT `category_id`
            FOREIGN KEY (`category_id`)
            REFERENCES `argo_project_01_2`.`categories` (`id`)
            ON DELETE NO ACTION
            ON UPDATE NO ACTION,
          CONSTRAINT `subcategory_id`
            FOREIGN KEY (`subcategory_id`)
            REFERENCES `argo_project_01_2`.`subcategories` (`id`)
            ON DELETE NO ACTION
            ON UPDATE NO ACTION)
        ENGINE = InnoDB

SQL script execution finished: statements: 9 succeeded, 1 failed

Fetching back view definitions in final form.
Nothing to fetch

查询有什么问题?

1 个答案:

答案 0 :(得分:1)

我认为可以通过将约束名称“category_id”和“subcategory_id”更改为例如“fk_category_id”和“fk_subcategory_id”来解决问题。

编辑: 您还可以删除“category_id_idx”和“subcategory_id_idx”索引,因为外键会自动生成索引。