问题
I have two table second
and third
second_id(PRIMARY KEY) second_name
1 .........
2 .......
3 .........
third_id(PRIMARY KEY) third_name second_id(FOREIGN KEY for second.second_id)
1 ..... 1
2 ..... 1
3 ..... 1
4 ..... 2
5 ..... 2
Now i want to delete a row fromsecond
where second_id=2
(DELETE FROM second WHERE second_id=2
) but it does not work. It says Successful 0 row(s) affected
What is more is, it happened after i append a foreign key to third.second_id
(i added foreign key after table is created).
回答1:
You will have to delete the rows in third
table with second_id = 2 and then delete the rows from second
with id = 2 or have ON DELETE CASCADE
in the foreign key constraint
回答2:
You can't delete a row from second
because one of it's values is being used in third
. That's a Foreign Key rule.
But you can cascade the foreign key in a was that if you delete a row from second
, all rows in third
which uses this value will also be deleted, or you can set them to null
.
This manual from MYSQL can tell you how to properly use ON DELETE
and ON UPDATE
, and then you can pick up the best option for you.
Look up for Referential Actions
Edit:
You can't add ON DELETE CASCADE to an existing foreign key, so you will have to drop it first.
alter table third drop foreign key third_foreign
Then
alter table third add constraint third_foreign foreign key (second_id) references second(second_id) on delete cascade;
来源:https://stackoverflow.com/questions/34501590/i-cant-delete-row-after-append-it-a-foreign-key