gpt4 book ai didi

MySQL innodb - 外键 : only 1st works?

转载 作者:可可西里 更新时间:2023-11-01 07:02:04 26 4
gpt4 key购买 nike

我在下面的示例中无法创建 customers_b。错误代码 1005/错误号:121。但是,如果我先创建 customers_b 而不是 customers_a,则不会创建 customers_a。

怎么了?为什么我不能将多个 FK 链接到 PK“id_state”?谢谢!

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

DROP SCHEMA IF EXISTS `testdb` ;
CREATE SCHEMA IF NOT EXISTS `testdb` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
USE `testdb` ;

-- -----------------------------------------------------
-- Table `testdb`.`state`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `testdb`.`state` ;

CREATE TABLE IF NOT EXISTS `testdb`.`state` (
`id_state` INT NOT NULL,
`abbr` CHAR(2) NOT NULL,
PRIMARY KEY (`id_state`),
UNIQUE INDEX `id_state_UNIQUE` (`id_state` ASC))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `testdb`.`customers_a`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `testdb`.`customers_a` ;

CREATE TABLE IF NOT EXISTS `testdb`.`customers_a` (
`id_customer` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
`addr_state` INT NOT NULL,
PRIMARY KEY (`id_customer`),
CONSTRAINT `fk_state`
FOREIGN KEY (`addr_state`)
REFERENCES `testdb`.`state` (`id_state`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;


-- -----------------------------------------------------
-- Table `testdb`.`customers_b`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `testdb`.`customers_b` ;

CREATE TABLE IF NOT EXISTS `testdb`.`customers_b` (
`id_customer` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
`addr_state` INT NOT NULL,
PRIMARY KEY (`id_customer`),
CONSTRAINT `fk_state`
FOREIGN KEY (`addr_state`)
REFERENCES `testdb`.`state` (`id_state`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;

最佳答案

您不能对两个约束使用相同的名称 fk_state。给其中一个取一个不同的名字。

CREATE TABLE IF NOT EXISTS `customers_b` (
`id_customer` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
`addr_state` INT NOT NULL,
PRIMARY KEY (`id_customer`),
CONSTRAINT `fk_state_b`
FOREIGN KEY (`addr_state`)
REFERENCES `state` (`id_state`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;

关于MySQL innodb - 外键 : only 1st works?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22208143/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com