将外语添加到我的表

时间:2016-04-12 14:27:57

标签: mysql

我想将外键添加到person_id,所以当我在级联(person_id)上删除时,它也会删除我的address_id和我的cv_id。现在我的问题是当我在我的详细信息页面上删除它只删除人值而不是地址和cv两个tabels地址和cv与人有关系

-- MySQL Script generated by MySQL Workbench
-- 04/12/16 16:22:18
-- Model: New Model    Version: 1.0
-- MySQL Workbench Forward Engineering

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';

-- -----------------------------------------------------
-- Schema persons
-- -----------------------------------------------------

-- -----------------------------------------------------
-- Schema persons
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `persons` DEFAULT CHARACTER SET utf8 ;
USE `persons` ;

-- -----------------------------------------------------
-- Table `persons`.`address`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `persons`.`address` (
`address_id` INT(11) NOT NULL AUTO_INCREMENT,
`address_street` VARCHAR(45) NULL,
`address_housenumber` VARCHAR(4) NULL,
`address_zipcode` VARCHAR(6) NULL,
`address_city` VARCHAR(45) NULL,
`address_state` VARCHAR(45) NULL,
 PRIMARY KEY (`address_id`))
ENGINE = InnoDB;


-- -----------------------------------------------------
-- Table `persons`.`cv`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `persons`.`cv` (
`cv_id` INT NOT NULL AUTO_INCREMENT,
`cv_name` VARCHAR(255) NULL,
`cv_path` VARCHAR(255) NULL,
`cv_type` VARCHAR(255) NULL,
 PRIMARY KEY (`cv_id`))
 ENGINE = InnoDB;


-- -----------------------------------------------------
-- Table `persons`.`person`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `persons`.`person` (
`person_id` INT(11) NOT NULL,
`person_firstname` VARCHAR(45) NULL,
`person_lastname` VARCHAR(45) NULL,
`person_email` VARCHAR(45) NULL,
`person_phonenumber` INT(10) NULL,
`person_cv` INT(11) NULL,
`person_address` INT(11) NULL,
 PRIMARY KEY (`person_id`),
INDEX `address_id_idx` (`person_address` ASC),
INDEX `cv_id_idx` (`person_cv` ASC),
CONSTRAINT `address_id`
FOREIGN KEY (`person_address`)
REFERENCES `persons`.`address` (`address_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `cv_id`
FOREIGN KEY (`person_cv`)
REFERENCES `persons`.`cv` (`cv_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;


SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

2 个答案:

答案 0 :(得分:1)

您已将外键设置为ON DELETE NO ACTION,因此删除时无操作

如果要在删除父行时删除相关行,请使用ON DELETE CASCADE

答案 1 :(得分:-1)

我建议您不要删除数据以保持一致性。

让您的应用查询拥有deleted = 0

刚刚删除""您的表格上的字段+设置ON DELETE RESTRICT以防止意外删除时数据丢失。

P.S。设置ON UPDATE CASCADE以保持关系的灵活性。

但如果你坚持,请找到:Multi-Table Deletes