1

我使用 MySQL 服务器 5.5;MySQL 工作台 5.2 CE;WinXp SP3;我创建了 2 个表:

CREATE  TABLE IF NOT EXISTS `mydb`.`Address` (
  `AddressID` INT NOT NULL AUTO_INCREMENT ,
  `Country` VARCHAR(45) NOT NULL ,
  `City` VARCHAR(45) NOT NULL ,
  `Region` VARCHAR(45) NOT NULL ,
  `PostalCode` VARCHAR(12) NOT NULL ,
  `Address1` VARCHAR(100) NOT NULL ,
  PRIMARY KEY (`AddressID`) )
ENGINE = InnoDB;


CREATE  TABLE IF NOT EXISTS `mydb`.`Customers` (
  `CustomerID` INT NOT NULL AUTO_INCREMENT ,
  `FirstName` VARCHAR(45) NOT NULL ,
  `LastName` VARCHAR(45) NOT NULL ,
  `Email` VARCHAR(500) NOT NULL ,
  `Password` VARCHAR(500) NOT NULL ,
  `RegistrationDate` TIMESTAMP NULL ,
  `CustomerCellPhone` VARCHAR(20) NULL ,
  `AddressID` INT NULL ,
  PRIMARY KEY (`CustomerID`) ,
  INDEX `AddressID_idx` (`AddressID` ASC) ,
  UNIQUE INDEX `Email_UNIQUE` (`Email` ASC) ,
  CONSTRAINT `CustomerAddressID`
    FOREIGN KEY (`AddressID` )
    REFERENCES `mydb`.`Address` (`AddressID` )
    ON DELETE RESTRICT
    ON UPDATE CASCADE)
ENGINE = InnoDB;

基本上,“客户”表包含外键约束,它不起作用。理论上,如果我将数据插入两个表中,我不会删除“地址”,因为“客户”依赖于它:

insert into Address SET Country = 'Zimbabwe',
                        City = 'Harare',
                        Region = 'Mashonaland East Province',
                        PostalCode = '777',
                        Address1 = 'square 777 - 777';

insert into Customers SET FirstName = 'John',
                          LastName ='Doe',
                          Email = 'john@doe.com',
                          Password = '12345',
                          RegistrationDate = now(),
                          CustomerCellPhone = 123456789,
                          AddressID = 1;

'顾客'

CustomerID    FirstName   AddressID
1             John        1

'地址'

AddressID         Country          City   
1                 Zimbabwe         Harare

但是,我可以通过以下方式删除客户的地址:

DELETE FROM Address WHERE AddressID=1;

表“客户”没有参考(悬空指针)

CustomerID        FirstName       AddressID
1                 John            1 

空表“地址”

AddressID         Country         City    
---               ---             ---

问题是 'Customers' 将 NULL 引用到 'Address' 中,因为 'Address'.AddressID = 1 不存在。它没有给我任何错误。我能做些什么来修复这个错误?

4

1 回答 1

1

呼,重新启动 MySQL 服务器对我有帮助。

于 2013-02-11T10:20:31.497 回答