简体   繁体   English

mysql无法删除或更新父行:外键约束失败

[英]mysql cannot delete or update a parent row: a foreign key constraint fails

  CREATE TABLE LOCATION(
    street_address VARCHAR(40)   NOT NULL,
    postal_code    VARCHAR(12)  NOT NULL,
    city           VARCHAR(30)   NOT NULL,
     state_province VARCHAR(25)       NULL,
country_name   VARCHAR(40) NOT NULL,
    CONSTRAINT LOCATION_PK PRIMARY KEY(street_address, postal_code, city, 
country_name),
  CONSTRAINT LOCATION_CK UNIQUE(street_address, city, state_province, 
   country_name),
   CONSTRAINT LOCATION_FK FOREIGN KEY(country_name)
   REFERENCES COUNTRY(country_name) );


  CREATE TABLE DEPARTMENT(
 department_name VARCHAR(30) NOT NULL,
   street_address VARCHAR(40)    NOT NULL,
  postal_code    VARCHAR(12)  NOT NULL,
     city           VARCHAR(30) NOT NULL,
   country_name   VARCHAR(40) NOT NULL,
 manager_id     DECIMAL(6)       NULL,
CONSTRAINT DEPARTMENT_PK PRIMARY KEY(department_name),
  CONSTRAINT DEPARTMENT_FK1 FOREIGN KEY(street_address, postal_code, city, 
 country_name)
 REFERENCES LOCATION(street_address, postal_code, city, country_name) );


    CREATE TABLE COUNTRY(
  country_name    VARCHAR(40)    NOT NULL,
  region_name     VARCHAR(25)     NOT NULL,
   CONSTRAINT COUNTRY_PK PRIMARY KEY(country_name),
   CONSTRAINT COUNTRY_FK FOREIGN KEY(region_name)
  REFERENCES REGION(region_name) );

as you can see from above 3 table , I need to update my department Accounting has been moved to a new location. 从上面的3表中可以看到,我需要更新我的部门会计已移至新位置。 The new address is 3 Subang 1, Subang Jaya, Petaling Jaya, Malaysia. 新地址是马来西亚八打灵再也Subang 1 Subang 1。 Post code is 31546. I already join those 3 table and yet it still cannot work. 邮政编码为31546。我已经加入了这3个表,但仍然无法正常工作。 Why? 为什么? Here is my sql update code : 这是我的SQL更新代码:

 UPDATE DEPARTMENT a
INNER JOIN LOCATION b ON a.street address = b.street address
AND a.postal_code = b.postal_code
  AND a.city=b.city
AND a.country_name = b.county_name
JOIN COUNTRY c
on b.country_name = c.country_name
SET a.street_address = 'subang 1 ,subang jaya ',
b.street_address = 'subang 1 ,subang jaya ',
a.postal_code = '31546',
b.postal_code = '31546',
a.city = 'PETALING JAYA ',
b.city = 'PETALING JAYA ',
a.country_name = 'MALAYSIA',
b.country_name = 'MALAYSIA',
 c.country_name = 'MALAYSIA'
WHERE DEPARTMENT = 'Accounting';

it give me cannot delete or update a parent row: a foreign key constraint fails which i dont understand why... can someone help me solve it ? 它使我无法删除或更新父行:外键约束失败,我不明白为什么...有人可以帮助我解决它吗?

If you want to update fields that are in another table foreign key constraint, you have to set the 'On update cascade' attribute to the foreign key. 如果要更新另一个表外键约束中的字段,则必须将“更新时的级联”属性设置为外键。

If you can't change the table structure, check this answer : How to update foreign key value in mysql database 如果您不能更改表结构,请检查以下答案: 如何更新mysql数据库中的外键值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM