2013-02-11 97 views
1

我使用MySQL Server 5.5; MySQL Workbench 5.2 CE; WinXp SP3; 我創建2個表:MySQL,參照完整性不起作用

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 = '[email protected]', 
          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  
---    ---    --- 

問題是'客戶'引用NULL到'地址',因爲'Address'.AddressID = 1不存在。它不會給我任何錯誤。我能做些什麼來修復這個bug?

+1

你有什麼版本的MySQL? – 2013-02-11 06:15:57

+0

MySQL服務器5.5 – 2013-02-11 07:57:49

+0

只需用'ON DELETE CASCADE'取代ON DELETE RESTRICT' – ravnur 2013-02-11 08:14:34

回答

1

唷,重啓MySQL服務器幫助我。