【问题标题】:Delete records from parent table and child table in mysql从mysql中的父表和子表中删除记录
【发布时间】:2015-08-12 09:21:26
【问题描述】:

我想用外键从表中删除记录。 表结构为:

CREATE TABLE `employees` (
`employeeNumber` int(11) NOT NULL,
`lastName` varchar(50) NOT NULL,
`firstName` varchar(50) NOT NULL,
`extension` varchar(10) NOT NULL,
`email` varchar(100) NOT NULL,
`officeCode` varchar(10) NOT NULL,
`reportsTo` int(11) DEFAULT NULL,
`jobTitle` varchar(50) NOT NULL,
PRIMARY KEY (`employeeNumber`),
KEY `reportsTo` (`reportsTo`),
KEY `officeCode` (`officeCode`),
CONSTRAINT `employees_ibfk_1` FOREIGN KEY (`reportsTo`) REFERENCES   `employees` (`employeeNumber`),
CONSTRAINT `employees_ibfk_2` FOREIGN KEY (`officeCode`) REFERENCES `offices` (`officeCode`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

第二张桌子:

Create Table">CREATE TABLE `offices` (
`officeCode` varchar(10) NOT NULL,
`city` varchar(50) NOT NULL,
`phone` varchar(50) NOT NULL,
`addressLine1` varchar(50) NOT NULL,
`addressLine2` varchar(50) DEFAULT NULL,
`state` varchar(50) DEFAULT NULL,
`country` varchar(50) NOT NULL,
`postalCode` varchar(15) NOT NULL,
`territory` varchar(10) NOT NULL,
PRIMARY KEY (`officeCode`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

我遇到了这个错误:

从 officeCode=7 错误代码的办公室中删除:1451。无法删除或更新父行:外键约束失败 (`classicmodels`.`employees`, CONSTRAINT `employees_ibfk_2` FOREIGN KEY (`officeCode`) REFERENCES ` office` (`officeCode`)) 0.093 秒

【问题讨论】:

    标签: mysql foreign-keys sql-delete


    【解决方案1】:

    您可以选择先删除子表条目,然后再删除到主表。像这样

    delete from employees where officeCode=7
    delete from offices where officeCode=7
    

    【讨论】:

      【解决方案2】:

      由于employees.officeCode 被声明为offices.officeCode 的外键,employees 表中使用的所有办公代码都必须存在于offices 表中。如果该办公室有任何员工,则您无法删除该办公室。

      您要么必须先删除这些员工,要么可以通过将 ON DELETE CASCADE 选项添加到 FOREIGN KEY 约束来告诉 MySQL 自动执行此操作。

      如果您允许employees.officeCodeNULL,您也可以使用ON DELETE SET NULL 将员工留在那里,但将他们的officeCode 设置为NULL

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-26
        • 1970-01-01
        • 2010-11-02
        • 2019-03-08
        相关资源
        最近更新 更多