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. The new address is 3 Subang 1, Subang Jaya, Petaling Jaya, Malaysia. Post code is 31546. I already join those 3 table and yet it still cannot work. Why? Here is my sql update code :
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.